Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

A colleague benchmarks two implementations with

Java
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) compute(i);

and reports the time. Why are the results unreliable and how would you benchmark properly?

The loop measures mostly JVM warm-up: the first calls run in the interpreter and are compiled partway through. If compute's result is not used, the JIT may also remove the work entirely or fold it into constants, and a single short run is easily skewed by garbage collection and other activity. We benchmark properly with JMH, which handles warm-up, separate forks, dead code elimination through Blackhole and returned values, and statistics, using realistic inputs and the same JVM flags for both implementations.

Why this question is asked

Comparing two implementations with System.nanoTime() around a loop looks reasonable, and the code is short enough that nobody questions the numbers. But the JVM is not a simple machine that runs our code line by line, and a hand-written timing loop can easily measure the compiler instead of the code. Interviewers use this example to see whether we know why, and whether we can set up a trustworthy benchmark instead. In this answer, we will look at the colleague's code, go through each reason the result is unreliable, and then rewrite it as a proper JMH benchmark.

1The Benchmark We Were Shown

Here is the colleague's code, with two implementations measured one after the other.

Java
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) computeA(i);
long a = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < 1000; i++) computeB(i);
long b = System.nanoTime() - start;
System.out.println("A: " + a / 1000 + " ns/op"); // A: 2140 ns/op
System.out.println("B: " + b / 1000 + " ns/op"); // B: 310 ns/op -> "B is 7x faster"

The conclusion sounds clear, but each of the numbers can be wrong for reasons that have nothing to do with A or B. Let us go through them.

2Problem 1: Warm-Up Dominates the Measurement

HotSpot runs new methods in the interpreter first and only compiles them after they have been called many times. A thousand calls is often not even enough to reach C2, the optimizing compiler. So the loop for A runs mostly interpreted, while the compiler threads work in the background.

The order makes it worse. By the time B runs, many shared methods that A also used, such as collections, string handling and math helpers, are already compiled. B gets a warm JVM, A got a cold one. If we swapped the two loops, we might see the opposite result. That alone can explain a seven-fold difference.

3Problem 2: The JIT May Delete or Fold the Work

The loop calls computeA(i) and throws the result away. If computeA has no side effects and C2 inlines it, the JIT can prove that nothing ever uses the result and remove the computation, which is called dead code elimination. The loop then measures an empty loop, which is why one implementation can suddenly look impossibly fast.

A related effect is constant folding. If the input were a constant, the JIT could compute the answer once at compile time. And because the loop bounds are fixed, C2 may unroll the loop or move work out of it in ways that do not happen when the code runs inside the real application.

Java
for (int i = 0; i < 1000; i++) computeB(i); // result unused: after inlining, may compile to nothing
int x = 42;
long r = computeB(x); // constant input: the result may be folded at compile time

4Problem 3: One Short Run Is Noise

One thousand calls of a fast method take well under a millisecond in total. In that window, a single garbage collection pause, a compilation finishing, a timer interrupt or another process on the machine can change the result by more than the difference we are trying to measure. Running once gives a single sample with no idea of the spread, so we cannot tell a real 10 percent improvement from random variation.

So we need three things: enough warm-up for the code to reach its steady compiled state, a way to stop the JIT from deleting the work, and many measurements across several fresh JVMs with a statistic and an error margin. That is what JMH provides.

5Rewriting It With JMH

JMH, the Java Microbenchmark Harness, is the OpenJDK project's tool for exactly this. We put each implementation in a method annotated with @Benchmark, and JMH generates the timing loop for us, written so the JIT cannot optimize it away.

Java
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1) // 5 x 1 s unmeasured, so C1 and C2 finish
@Measurement(iterations = 10, time = 1) // 10 x 1 s measured
@Fork(3) // 3 fresh JVMs, so one JVM's JIT luck does not decide
@State(Scope.Benchmark)
public class ComputeBench {
@Param({"10", "1000", "100000"}) // realistic input sizes
int size;
int[] input;
@Setup public void setup() { input = new Random(42).ints(size).toArray(); }
@Benchmark public long a() { return Impl.computeA(input); } // returned value is consumed by JMH
@Benchmark public void b(Blackhole bh) { bh.consume(Impl.computeB(input)); } // or consume explicitly
}
// Benchmark (size) Mode Cnt Score Error Units
// ComputeBench.a 1000 avgt 30 812.4 +- 9.1 ns/op
// ComputeBench.b 1000 avgt 30 779.0 +- 11.6 ns/op
Step throughWhat JMH does for each benchmark method
  1. Fork a fresh JVMsame flags for every benchmark
  2. Run warm-up iterationsresults discarded
  3. Run measured iterationsresults consumed so they cannot be eliminated
  4. More forks to run?
    YesFork again and repeatNoCombine all samples
  5. Report score and errormean with confidence interval

5 steps in order. Play them, or step through them one at a time.

Every benchmark gets its own cold start and its own warm-up.

Notice what changed. Warm-up runs before any measurement, so we measure compiled code. Each benchmark runs in fresh forked JVMs, so A cannot warm up shared code for B. Returning the value, or passing it to Blackhole.consume, makes the result look used to the JIT, so the work cannot be deleted. The inputs live in a @State object and are not compile-time constants, so they cannot be folded. And the output shows a score with an error margin over 30 samples. In this example, the real difference turns out to be about 4 percent, not seven times, and the error bars nearly touch.

6Getting Realistic Results

JMH removes the measurement traps, but it cannot choose our inputs. A benchmark with 10 elements says nothing about 100,000, so we use @Param with sizes and data shapes taken from production. If the real code sees several implementation types at a call site, the benchmark should too, or the JIT will inline more than it can in production.

We also compare both implementations under the same JVM version and flags as production, including the garbage collector and heap size, and on a quiet machine rather than a busy laptop. JMH's profilers, such as -prof gc for allocation rate, help explain why one version is faster. Finally, a microbenchmark answers a narrow question; before a big rewrite, we confirm the gain in a load test of the whole service.

7Follow-up questions

Why does JMH fork a new JVM instead of running everything in one process?

Because the JIT's decisions depend on everything that ran before. If benchmark A runs first, it changes the profiles of shared methods, the classes loaded and the heap state that benchmark B inherits. A fresh JVM per fork gives each benchmark the same starting point, and running several forks shows how much results vary between JVM runs.

Is it enough to just add a warm-up loop before the timed loop?

It helps but does not fix the other problems. The JIT can still eliminate unused results, the timed run is still short and noisy, and order effects between implementations remain. Writing a correct harness by hand is surprisingly hard, which is why JMH exists.

When is System.nanoTime() the right tool?

For measuring real elapsed time of large operations in the running application, such as how long a request or a batch takes, where we record many samples into a metrics histogram. It is the wrong tool for comparing two small pieces of code in isolation.

8Conclusion

In this answer, we saw why a hand-written nanoTime loop gives unreliable numbers: it measures warm-up, the JIT may delete or fold unused work, and one short run is mostly noise. We then rewrote it with JMH, which warms up, forks fresh JVMs, consumes results, and reports statistics, and we noted that realistic inputs and identical JVM flags are still our job.

What to say in the interviewAbout 90 seconds aloud

Open with

The numbers from that loop are not trustworthy for three reasons. First, a thousand calls is mostly warm-up: the methods start in the interpreter and get compiled during the loop, and because B runs second it inherits a JVM where shared code is already compiled, so the order alone could explain the difference.

Then, if they want more

Second, the results of compute are thrown away, so once the JIT inlines the method it can prove the work is unused and remove it, or fold it when inputs are constants, and then we are timing an empty loop.

Third, it is one short run, well under a millisecond, so a GC pause or compilation finishing can swing it more than the difference we care about, and we have no idea of the spread. I would rewrite it with JMH.

Each implementation becomes a @Benchmark method, JMH runs warm-up iterations before measuring, runs each benchmark in several forked JVMs so they do not affect each other, and the returned value or a Blackhole stops dead code elimination. It reports a score with an error margin.

I would use @Param with realistic input sizes and data, run with the same JVM version and flags as production on a quiet machine, and use the gc profiler to see allocation. And if the decision is important, I would confirm the gain in a load test of the real service.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A colleague benchmarks two implementations with": https://scrivio-interview-library.netlify.app/java/jvm-architecture/78427216ef/