Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Java micro-benchmark on virtual method calls.
import com.google.caliper.SimpleBenchmark;
interface iface {
int foo();
}
class base implements iface {
public int foo() {
return (int) System.nanoTime();
}
}
final class sealed extends base {
}
final class sealedfinal extends base {
public final int foo() {
return super.foo();
}
}
public final class devirt extends SimpleBenchmark {
public static void main(String[] a) {
int n = 0;
final iface i = new base();
n ^= i.foo();
final base b = new base();
n ^= b.foo();
final sealed s = new sealed();
n ^= s.foo();
if (n == 0) {
System.exit(42);
}
}
public int timeInvokeInterfaceBase(final int n) {
int d = 0;
final iface o = new base();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
public int timeInvokeInterfaceFinal(final int n) {
int d = 0;
final iface o = new sealed();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
public int timeInvokeVirtualBase(final int n) {
int d = 0;
final base o = new base();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
public int timeInvokeVirtualFinal(final int n) {
int d = 0;
final base o = new sealed();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
public int timeInvokeFinal(final int n) {
int d = 0;
final sealed o = new sealed();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
public int timeInvokeFinalFinal(final int n) {
int d = 0;
final sealedfinal o = new sealedfinal();
for (int i = 0; i < n; i++) {
d ^= o.foo();
}
return d;
}
}
Owner

tsuna commented Feb 6, 2012

Results on MacBook with Intel Core 2 Duo @ 2.66Ghz and Sun JVM 1.6.0_26:

 0% Scenario{vm=java, trial=0, benchmark=InvokeInterfaceBase} 60.39 ns; ?=2.75 ns @ 10 trials
17% Scenario{vm=java, trial=0, benchmark=InvokeInterfaceFinal} 60.75 ns; ?=2.35 ns @ 10 trials
33% Scenario{vm=java, trial=0, benchmark=InvokeVirtualBase} 60.73 ns; ?=2.44 ns @ 10 trials
50% Scenario{vm=java, trial=0, benchmark=InvokeVirtualFinal} 60.44 ns; ?=2.00 ns @ 10 trials
67% Scenario{vm=java, trial=0, benchmark=InvokeFinal} 60.79 ns; ?=2.18 ns @ 10 trials
83% Scenario{vm=java, trial=0, benchmark=InvokeFinalFinal} 60.67 ns; ?=1.84 ns @ 10 trials

           benchmark   ns linear runtime
 InvokeInterfaceBase 60.4 =============================
InvokeInterfaceFinal 60.8 =============================
   InvokeVirtualBase 60.7 =============================
  InvokeVirtualFinal 60.4 =============================
         InvokeFinal 60.8 ==============================
    InvokeFinalFinal 60.7 =============================

vm: java
trial: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment