Concatenation in Java

I wanted to know which took less time when concatenating a string in Java:

  1. concatenation by use of the + sign or
  2. 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.

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));
	}

}

Leave a comment

Your email address will not be published. Required fields are marked *