Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java fastest way to concatenate strings, integers and floats

What is the most performant way to build strings from strings, integers and floats? currently I'm doing this and it uses a lot of cpu time.

String frame = this.frameTime + ":" +
    this.player.vertices[0].x + "," +
    this.player.vertices[0].y + "," +
    this.player.activeAnimId + "," +
    (int)this.player.virtualSpeed + "," +
    this.map.getCurrentTime() + 
    (this.player.frameSound == -1 ? "" : "," + this.player.frameSound) +
    (this.player.frameDecal.equals("") ? "" : "," + this.player.frameDecal) +
    ";";

Is there a way to do this faster?

like image 628
Andreas Linden Avatar asked Apr 19 '12 18:04

Andreas Linden


People also ask

Which is the fastest way to concatenate many strings in Java?

Because of this size declaration, the StringBuilder can be a very efficient way to concatenate Strings. It's also worth noting that the StringBuffer class is the synchronized version of StringBuilder.

Which is the efficient way of concatenating the string in Java?

StringBuilder is the winner and the fastest way to concatenate Strings. StringBuffer is a close second, because of the synchronized method, and the rest of them are just 1000 times slower than them.

What is the most efficient way to concatenate many strings together?

Concatenate Many Strings using the Join As shown above, using the join() method is more efficient when there are many strings.

How do you concatenate strings and integers in Java?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.


3 Answers

That should already be fast - it'll use StringBuilder internally for concatenation. Arguably using StringBuilder explicitly could eliminate the concatenation of empty strings, but it's not likely to make a big difference.

How often are you doing this, anyway? It must be pretty often, for it to be a bottleneck... do you really need to do it that often?

EDIT: For those who are saying "Use StringBuilder, it'll be faster" - consider this code:

public class Test
{
    public static void main(String[] args)
    {
        int x = 10;
        int y = 20;
        int z = 30;
        String foo = x + "," + y + "," + z + ";";
        System.out.println(foo);
    }
}

Compile that, then use javap -c to see what the compiler generates...

like image 102
Jon Skeet Avatar answered Oct 14 '22 08:10

Jon Skeet


Use a StringBuilder.

String string = new StringBuilder("abcd").append(23).append(false).append("xyz").toString();
like image 21
adarshr Avatar answered Oct 14 '22 08:10

adarshr


You could try using a StringBuilder.

(However, most Java compilers worth their salt will automatically optimize the code you've listed to use StringBuilder behind the scenes.)

like image 44
Tony the Pony Avatar answered Oct 14 '22 10:10

Tony the Pony