getClass()
演算子よりもand==
演算子を使用すると、パフォーマンスが向上しinstanceOf
ます。
Object str = new Integer("2000");
long starttime = System.nanoTime();
if(str instanceof String) {
System.out.println("its string");
} else {
if (str instanceof Integer) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime()-starttime));
starttime = System.nanoTime();
if(str.getClass() == String.class) {
System.out.println("its string in equals");
} else {
if(str.getClass() == Integer.class) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime()-starttime));
どちらを使用するか、またはどちらを使用するかのガイドラインはありますgetClass()
かinstanceOf
?
シナリオを考えると、一致する正確なクラス、つまりString
、Integer
(これらは最終クラスです)などを知っています。
instanceOf
オペレーターの悪い習慣を使用していますか?