Last active
December 11, 2015 18:29
-
-
Save agarciadom/4642290 to your computer and use it in GitHub Desktop.
Small test program for checking the performance impact of an instanceof call (tl;dr: not much)
This file contains hidden or 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
| class A {} | |
| class B extends A {} | |
| class C {} | |
| public class TestInstanceOf { | |
| public static void main(String[] args) { | |
| final B b = new B(); | |
| final C c = new C(); | |
| int i = 0, nA = 0; | |
| final long start = System.nanoTime(); | |
| for (; i < 1000000000; ++i) { | |
| // just in case, try both positive and negative cases | |
| final Object o = (i & 1) == 0 ? b : c; | |
| if (o instanceof A) { | |
| // do something here so the compiler doesn't try to optimize it out | |
| ++nA; | |
| } | |
| } | |
| System.out.println("Total time in ns: " + (System.nanoTime() - start)/((double)i)); | |
| System.out.println("Number of As (half of instanceof calls): " + nA); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And more results, this time on an i5-3470 CPU @ 3.20GHz :
% java -version
java version "1.6.0_27"
OpenJDK Runtime Environment (IcedTea6 1.12.5) (6b27-1.12.5-1ubuntu1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)
% java -cp . TestInstanceOf
Total time in ns: 0.863790555
Number of As (half of instanceof calls): 500000000