Created
February 6, 2012 07:44
-
-
Save tsuna/1750505 to your computer and use it in GitHub Desktop.
Java micro-benchmark on virtual method calls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on MacBook with Intel Core 2 Duo @ 2.66Ghz and Sun JVM 1.6.0_26: