I wanted to know which took less time when concatenating a string in Java:
- concatenation by use of the
+sign or - by use of
String.format
So I wrote some code to time the difference (see below). I tried running with line 22 and then line 23. I started a timer, called msg a million times, stopped the timer and recorded how long it took. I did this six times for line 22 and 23. I sorted the results for each method in ascending order (see table below).
Turns out just using the plus in this scenario is a little faster.
| plus | String.format |
|---|---|
| 2.888 | 3.616 |
| 2.951 | 3.686 |
| 3.085 | 3.885 |
| 3.131 | 3.965 |
| 3.194 | 3.984 |
| 3.228 | 4.112 |
import org.apache.commons.lang3.time.StopWatch;
public class Main {
public static void main(String[] args) {
StopWatch mySW = new StopWatch();
System.out.println("Running...");
mySW.start();
for (int i = 1; i <= 1_000_000; i++) {
msg(i);
}
mySW.stop();
System.out.println("Finished.");
System.out.println("Time is: " + mySW.getTime() + "ms");
}
private static void msg(int loopNum) {
// System.out.println("loop number: " + loopNum);
System.out.println(String.format("loop number: %d", loopNum));
}
}