Java: compare two numbers directly (a < b) vs by subtracting (a-b < 0)

Viewed 271

In the books and others code, I can see sometimes

if (a-b < 0) ... 

instead of just simple and better readable

if (a < b) ... 

What is the reason for that? Is there any performance gain? Or this is just a personal style of coding?...

PS Made the quick naive test with jmh and didn't find any performance gain:

@Fork(value = 1)
@Warmup(time = 1)
@Measurement(time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class Main {

  private long a,b;

  @Setup(value = Level.Invocation)
  public void setup(){
    a = Math.round(Math.random()*100);
    b = Math.round(Math.random()*100);
  }

  @Benchmark
  public void directCompare(Blackhole bh) {
    bh.consume(a < b);
  }

  @Benchmark
  public void substractCompare(Blackhole bh) {
    bh.consume(a - b < 0);
  }

Benchmark              Mode  Cnt   Score   Error  Units
Main.directCompare     avgt    5  27.718 ± 2.778  ns/op
Main.substractCompare  avgt    5  27.055 ± 0.707  ns/op
0 Answers
Related