I was wondering if there was any significative difference on checking if an object is null in java with direct comparison, or by using the Objects.isNull() method.
public class Test {
public final static Long ITERATIONS = 100000000L;
@Test
public void noFnCalls() {
balong startTime = System.currentTimeMillis();
Object x = new Object();
Long i;
for (i = 0L; i < ITERATIONS; i++) {
boolean t = x == null;
}
long estimatedTime = System.currentTimeMillis() - startTime;
System.out.println("noFnCalls ellapsed time: " + estimatedTime);
}
@Test
public void withFnCalls() {
long startTime = System.currentTimeMillis();
Object x = new Object();
Long i;
for (i = 0L; i < ITERATIONS; i++) {
boolean t = Objects.isNull(x);
}
long estimatedTime = System.currentTimeMillis() - startTime;
System.out.println("withFnCalls ellapsed time: " + estimatedTime);
}
}
And surprisingly, at least for me, it always takes more time to finish the "noFnCalls". I was expecting pretty much the opposite result, since it results into a method call, using stack.
This is the output: (Changes every time, obviously, but always with "noFnCalls" higher)
noFnCalls ellapsed time: 583
withFnCalls ellapsed time: 463
Why is this produced?