Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation without allocation in java

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?

like image 571
pedja Avatar asked May 28 '15 09:05

pedja


People also ask

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.

Can you use += with strings in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java.


1 Answers

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.

like image 97
ci_ Avatar answered Oct 20 '22 09:10

ci_