java 8 – writing a timer

A member at CodeRanch asked a question that prompted me to write a qucik program to determine which of two String operations were faster. This is the first time my instinct was to use Java 8 functionality to do it.

The interesting features:

  1. Uses Instant and Duration instead of System.currentTimeMillis().
  2. Uses functional programming to pass the expression to run to the timer rather than duplicating the timer logic or using a subclass
  3. Uses underscores to make # iterations more readable. (Ok, this is Java 7 not Java 8)
public class PlayTest {

	public static void main(String[] args) throws Exception {

		timer("string concatenation", () -> "/root/" + getFolderName()
				+ "/subfolder");
		timer("string format",
				() -> String.format("/root/%s/subfolder", getFolderName()));

	}

	private static void timer(String message, Supplier<String> candidate) {
		Instant start = Instant.now();
		int times = 1_000_000;

		for (int i = 0; i < times; i++) {
			candidate.get();
		}
		Instant end = Instant.now();
		System.out.println(message + " : " + Duration.between(start, end));
	}

	private static String getFolderName() {
		return "foo";
	}

}

The old way (for comparison)

public static void oldWay() {
		long before = System.currentTimeMillis();
		int times = 1_000_000;

		for (int i = 0; i < times; i++) {
			String s = "/root/" + getFolderName() + "/subfolder";
		}
		long after = System.currentTimeMillis();
		System.out.println("String concatenation: " + (after - before));
	}

The output

The output is also clearer.

string concatenation : PT0.5533S

Vs

string concatenation : 553

I actually get units of time without doing anything special now. And in case you are wondering, the conclusion is that string concatenation is faster. I expected that. It was way faster than I expected though. Twenty times faster.