How to consume primitive values in a loop?

Roman Leventov leventov.ru at gmail.com
Tue Feb 20 16:08:17 UTC 2018


When the body of a benchmark contains a loop (I
see JMHSample_11_Loops.java, but sometimes...  often... loop is needed)
What is the better way to consume primitives, produced in the loop?

1) Summing (XORing) them and consume (or return) the dummy value after the
loop:

@Benchmark
public long someBench() {
  int sum = 0;
  for (...) {
     sum += someValue();
  }
  return sum;
}

2) Calling blackhole.comsume() on each iteration:

@Benchmark
public void someBench(Blackhole bh) {
  for (...) {
     bh.consume(someValue());
  }
}

My concern about the second option is that bh.consume() may skew the
results, because the production loop doesn't contain this (potentially
costly) call.


More information about the jmh-dev mailing list