Glen Mazza wrote:
Well, instanceof is slower I believe, but better self-commenting.
[J.Pietschmann]
Instanceof is exactly as fast as a simple function call after warm-up.
That is not what I remembered, so I made a small test program and ran it with 3 different versions of jdk:
[/d/fop] /c/java/jdk1.2.2/jre/bin/java.exe -cp . x false method call 160 true method call 170 false instanceof 581 true instanceof 581
[/d/fop] /c/java/jdk1.3.1_03/jre/bin/java.exe -cp . x false method call 16614 true method call 881 false instanceof 1162 true instanceof 2083
[/d/fop] /c/java/j2sdk1.4.2_02/bin/java.exe -cp . x false method call 581 true method call 661 false instanceof 2153 true instanceof 2734
I really don't know what to conclude from this test, but at least I'm glad I didn't mentioned performance as the reason why I prefer the get<type> way of testing for subclasses.
I'm surprised of the slow performance of calling non-overridden methods in jdk1.3.1. I don't have any explanation for that.
regards, finn
import java.io.*; import java.net.*;
public class x { public static final int ITERS = 100000000;
public static void main(String[] args) throws Exception {
Prop prop = new Prop();
Prop stringprop = new StringProp(); // Warm up the JIT.
testCall(prop);
testInstanceOf(prop);long now;
now = System.currentTimeMillis();
testCall(prop);
System.out.println("false method call " +
(System.currentTimeMillis() - now)); now = System.currentTimeMillis();
testCall(stringprop);
System.out.println("true method call " +
(System.currentTimeMillis() - now)); now = System.currentTimeMillis();
testInstanceOf(prop);
System.out.println("false instanceof " +
(System.currentTimeMillis() - now)); now = System.currentTimeMillis();
testInstanceOf(stringprop);
System.out.println("true instanceof " +
(System.currentTimeMillis() - now));}
public static void testInstanceOf(Prop prop) {
for (int i = ITERS; i >= 0; i--) {
boolean x = prop.getString() != null;
}
} public static void testCall(Prop prop) {
for (int i = ITERS; i >= 0; i--) {
boolean x = prop instanceof StringProp;
}
} public static class Prop {
public String getString() {
return null;
}
} public static class StringProp extends Prop{
String value = "a string";
public String getString() {
return value;
}
}
}