Should I use Java’s String.format() if performance is important?

I took hhafez code and added a memory test:

private static void test() {
    Runtime runtime = Runtime.getRuntime();
    long memory;
    ...
    memory = runtime.freeMemory();
    // for loop code
    memory = memory-runtime.freeMemory();

I run this separately for each approach, the ‘+’ operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches.
I added more concatenations, making the string as “Blah” + i + “Blah”+ i +”Blah” + i + “Blah”.

The result are as follow (average of 5 runs each):
Approach       Time(ms)  Memory allocated (long)
‘+’ operator     747           320,504
String.format  16484       373,312
StringBuilder  769           57,344

We can see that String ‘+’ and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use.
This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won’t get to clean the many string instances resulting of the ‘+’ operator.

And a note, BTW, don’t forget to check the logging level before constructing the message.

Conclusions:

  1. I’ll keep on using StringBuilder.
  2. I have too much time or too little life.

Leave a Comment