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?
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.
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.
Concatenate Many Strings using the Join As shown above, using the join() method is more efficient when there are many strings.
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.
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...
Use a StringBuilder
.
String string = new StringBuilder("abcd").append(23).append(false).append("xyz").toString();
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With