Skip to content

Instantly share code, notes, and snippets.

@agarciadom
Last active December 11, 2015 18:29
Show Gist options
  • Select an option

  • Save agarciadom/4642290 to your computer and use it in GitHub Desktop.

Select an option

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)
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);
}
}
@agarciadom
Copy link
Author

Here are my results:

$ java -version
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.5) (ArchLinux-6.b24_1.11.5-1-x86_64)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

$ javac TestInstanceOf.java && java -cp . TestInstanceOf
Total time in ns: 0.946371212
Number of As (half of instanceof calls): 500000000

@agarciadom
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment