I was experimenting with predicates. I tried to implement the predicate for serializing issues in distributed systems. I wrote a simple example where the test function just returns true. I was measuring the overhead, and I stumbled upon this interesting problem. Accessing array in for loop is 10 times slower compared to direct access.
class Test {
public boolean test(Object o) { return true; }
}
long count = 1000000000l;
Test[] test = new Test[3];
test[0] = new Test();
test[1] = new Test();
test[2] = new Test();
long milliseconds = System.currentTimeMillis();
for(int i = 0; i < count; i++){
boolean result = true;
Object object = new Object();
for(int j = 0; j < test.length; j++){
result = result && test[j].test(object);
}
}
System.out.println((System.currentTimeMillis() - milliseconds));
However, the following code is almost 10 times faster. What can be the reason?
milliseconds = System.currentTimeMillis();
for(int i=0 ; i < count; i++) {
Object object = new Object();
boolean result = test[0].test(object) && test[1].test(object) && test[2].test(object);
}
System.out.println((System.currentTimeMillis() - milliseconds));
Benchmark results on my i5.
4567 msec for for loop access
297 msec for direct access
!result && j < test.lengthand initializingboolean result = falseto have the same chance at short-circuiting?foo(), and the other one into a method calledbar(), and then call these methods, maybe 20 types, alternatingly, from yourmainmethod. For me, after a few calls, the methods will take exactly the same amount of time. (Starting withjava -server ...might help). The first method may be a tag more complex, which may be a reason for the JIT to kick in a bit later, but in the end, there is no difference.resultvariaible is not used, and the compiler could basically eliminate the whole program. And the fact that theresultvariable is read and written in the first approach, but only written in the second one may be another reason of why it's easier for the optimizer to figure out that the whole code is effectively useless...