I've read this post: Performance difference between Java 8 lambdas and anonymous inner classes and provided there article
and it there said:
Lambda invocation behaves exactly as anonymous class invocation
"Ok" I said and decided to write my own benchmark, I've used jmh
, here it is below (I've also added benchmark for method reference).
public class MyBenchmark {
public static final int TESTS_COUNT = 100_000_000;
@Benchmark
public void testMethod_lambda() {
X x = i -> test(i);
for (long i = 0; i < TESTS_COUNT; i++) {
x.x(i);
}
}
@Benchmark
public void testMethod_methodRefernce() {
X x = this::test;
for (long i = 0; i < TESTS_COUNT; i++) {
x.x(i);
}
}
@Benchmark
public void testMethod_anonymous() {
X x = new X() {
@Override
public void x(Long i) {
test(i);
}
};
for (long i = 0; i < TESTS_COUNT; i++) {
x.x(i);
}
}
interface X {
void x(Long i);
}
public void test(Long i) {
if (i == null) System.out.println("never");
}
}
And the results (on Intel Core i7 4770k) are:
Benchmark Mode Samples Score Score error Units
t.j.MyBenchmark.testMethod_anonymous thrpt 200 16,160 0,044 ops/s
t.j.MyBenchmark.testMethod_lambda thrpt 200 4,102 0,029 ops/s
t.j.MyBenchmark.testMethod_methodRefernce thrpt 200 4,149 0,022 ops/s
So, as you can see there is 4x difference between lambda and anonymous method invocation, where lambda is 4x slower.
The question is: what am I doing wrong or I have misunderstanding of performance theory about lambdas?
EDIT:
# VM invoker: C:\Program Files\Java\jre1.8.0_31\bin\java.exe
# VM options: <none>
# Warmup: 20 iterations, 1 s each
# Measurement: 20 iterations, 1 s each