What's faster: instanceof or isInstance?

坚强是说给别人听的谎言 提交于 2019-12-13 05:36:19

问题


Design questions aside, what performs faster on modern JVMs?

foo instanceof Bar

or

Bar.class.isInstance(foo)

Why?


回答1:


Class.isInstance is JVM intrinsic. It is compiled to exactly the same sequence as instanceof does (the proof from HotSpot source code: 1, 2). That is, they both are equal in terms of performance.




回答2:


foo instanceof Bar should be faster.

You can use Bar.class.isInstance(foo) if it's not clear at compile time which class you have.

consider the following:

void test(Object o1, Object o2) {
   o1.getClass().isInstance(o2);
}

In this exsample the JVM decides at runtime which class calls the method. With instanceof this is not possible.

So if you know the class at compile time you should use instanceof



来源:https://stackoverflow.com/questions/36435670/whats-faster-instanceof-or-isinstance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!