Different ways of String formatting in Java : Benchmarking

Java programmers use mostly the following three ways for formatting or building a string.

  1. String concatenation using + operator
  2. Using String.format
  3. Using StringBuilder

Functionally all these 3 ways will produce the same result but the question is “are all the 3 ways have the same time and space performance?“. I wrote small code snippet to benchmark these three ways.

public static long  stringConcat(int iterations) throws InterruptedException {
		String cersei = "Cersei";
		String nightKing = "Night King";
		long startTime = System.currentTimeMillis();
		for(int i=0; i<iterations; i++) {
		 if(i%2 == 0) {
			String s = i+" Who"+" will"+" kill " + cersei;
		 } else {
			 String s = i+" Is"+ " it " + nightKing;
		 }
		}
		long endTime = System.currentTimeMillis();
		return endTime-startTime;
	}

	public static long stringFormat(int iterations) {
		String cersei = "Cersei";
		String nightKing = "Night King";
		long startTime = System.currentTimeMillis();
		for(int i=0; i<iterations; i++) {
		 if(i%2 == 0) {
			String s = String.format("%d %s %s %s %s", i, "who", "will", "kill", cersei);
		 } else {
			 String s = String.format("%d %s %s %s", i,"is",  "it",  nightKing);
		 }

		}
		long endTime = System.currentTimeMillis();
		return endTime-startTime;
	}

	public static long stringBuilder(int iterations) {
		String cersei = "Cersei";
		String nightKing = "Night King";
		long startTime = System.currentTimeMillis();
		for(int i=0; i<iterations; i++) {
		 if(i%2 == 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(i).append(" who").append(" will").append(" kill ").append(cersei);
			String s = sb.toString();
		 } else {
			 StringBuilder sb = new StringBuilder();
				sb.append(i).append("Is").append(" it").append(nightKing);
				String s = sb.toString();
		 }

		}
		long endTime = System.currentTimeMillis();
		return endTime-startTime;
	}

Ran all 3 methods with an iteration count of 100000.

  1. String concatenation took ~110ms
  2. String.format took ~1600ms
  3. StringBuilder took ~80ms

String.format takes considerably more time because it internally uses the java.util.Formatter and creates several instances of Formatter and other utility Objects that consumes the considerable amount of CPU time and memory. Below is the screen shot of the profiling for this case. We can see that there lot of additional objects being created.

STringFormatProfile.jpg

Similarly I profiled the other methods as well and observed that String concatenation creates more objects than the StringBuilder.

In summary,

String concatenation and StringBuilder performs almost equal w.r.t time complexity but the StringBuilder performs better in terms of space complexity. If performance is a concern, never use String.format.