Is there a way to concatenate two Strings (not final) without allocating memory?
For example, I have these two Strings:
final String SCORE_TEXT = "SCORE: ";
String score = "1000"; //or int score = 1000;
When I concatenate these two strings, a new String
object is created.
font.drawMultiLine(batch, SCORE_TEXT + score, 50f, 670f);//this creates new string each time
Since this is done in the main game loop (executed ~60 times in one second), there are a lot of allocations.
Can I somehow do this without allocation?
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.
In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java.
The obvious solution is to not recreate the output String
on every frame, but only when it changes.
One way to do this is to store it somewhere outside your main loop and update it when a certain event happens, i.e. the "score" actually changes. In your main loop you then just use that pre-created String
.
If you can't/or don't want to have this event based approach, you can always store the "previous" score and only concatenate a new String when the previous score is different from the current score.
Depending on how often your score actually changes, this should cut out most reallocations. Unless of course the score changes at 60 fps, in which case this whole point is completely mute because nobody would be able to read the text you're printing.
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