如何在JAVA中实现instanceof? [英] How instanceof is implemented inside JAVA?
问题描述
现在,我正在编写一个ORM框架,并且非常在意性能.
Now I'm writing an ORM Framework and very care about performance.
在此框架中,我必须使用 instanceof
和 Class.isAssignableFrom
来检查类型的兼容性.
In this Framework , I have to use instanceof
and Class.isAssignableFrom
to check type compability.
所以我对 instanceof
和 Class.isAssignableFrom
到底有多慢?
推荐答案
如何在JAVA中实现instanceof?
How instanceof is implemented inside JAVA?
简短的答案是它取决于平台.
The short answer is that it is platform dependent.
长答案是,您应该能够通过编写一个使用 instanceof
的测试用例,以循环方式运行以确保其被JIT编译,然后转储来找出其实现方式.并检查本机代码.
The long answer is that you should be able to find out how it is implemented by writing a test case that uses instanceof
, running it in a loop to ensure it gets JIT compiled, and then dumping and examining the native code.
但是,我认为这不会特别有启发性.您真正想知道的是 instanceof
还是 Class.isAssignableFrom
更快.您可以通过仔细的微基准测试来衡量.
However, I don't think this is going to be particularly instructive. What you really want to know is whether instanceof
or Class.isAssignableFrom
is faster. You can measure this by careful micro-benchmarking.
FWIW,我预计您会发现 instanceof
更快.(我希望JIT编译器能够以无法优化反射版本的方式优化 instanceof
.)
FWIW, I predict that you will find that instanceof
is faster. (I expect that the JIT compiler would be able to optimize instanceof
in ways that it couldn't optimize the reflective version.)
但是,最后,我建议您在此阶段不要浪费时间进行这种优化.使用 instanceof
对此进行编码,然后等待直到有一些性能分析数据告诉您 instanceof
的使用确实是性能瓶颈.(关心性能"是非常好的……但是实际上,在性能成为关键问题之前,您还需要做更重要的事情.)
But lastly, I'd suggest that you don't waste your time with this level of optimization at this stage. Code this using instanceof
, and wait until you have some profiling data that tells you that your instanceof
usage is really a performance bottleneck. (It is all very well to "care about performance" ... but in reality there are more important things that you need to get right BEFORE performance becomes a key issue.)
这篇关于如何在JAVA中实现instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!