我发现使用时性能有所提高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()
or instanceOf
?
给定一个场景:我知道要匹配的确切类,即String
, Integer
(这些是期末课程)等等。
正在使用instanceOf
操作员的不良做法?
其性能的原因是instanceof
and getClass() == ...
不同的是,他们做的事情不同。
因此,建议忽略性能问题并使用能为您提供所需答案的替代方案。
正在使用instanceOf
操作员的不良做法?
不必要。过度使用其中任何一个instanceOf
or getClass()
may be“设计气味”。如果您不小心,您最终会得到这样的设计:添加新子类会导致大量代码返工。在大多数情况下,首选方法是使用多态性。
然而,在某些情况下,这些并不是“设计气味”。例如,在equals(Object)
您需要测试参数的实际类型,然后返回false
如果不匹配。最好使用getClass()
.
Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices https://www.satisfice.com/blog/archives/5164 if they haven't already done so.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)