改进可比性 比较性能
我分析了我的代码,发现我的类(实现了 Comparable
compareTo(Object)
我
compareTo(T)
认为速度减慢是因为该方法的虚拟表查找造成的。
有没有办法强制静态调用函数?(就像在非虚拟 C++ 方法中一样)
我仍然想使用 Comparable
接口,因为我使用 TreeSet
与此对象,我不想重写此代码。
编辑:不,我没有实现 compareTo(Object) - 这是由分析器自动生成和报告的
I profiled my code and found out that my class, which implements Comparable<T>
, spends 8x more cpu time in
compareTo(Object)
than in
compareTo(T)
I assume that the slowdown is because of virtual table lookup for this method.
Is there a way to force static invocation of the function? (like in non virtual C++ methods)
I still want to use the Comparable<T>
interface since I use TreeSet
with this object and I'd like not to rewrite this code.
EDIT: No, I didn't implement the compareTo(Object) - this was automatically generated and reported by the profiler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您看到
compareTo(Object)
的原因是因为 类型擦除。 它只是意味着在运行时不再需要类型信息来比较值。您速度放缓的原因很可能是
1)非常非常大的TreeSet,有很多元素
2) - 更有可能 - 你的compareTo方法做了一些昂贵的事情。 因为它被频繁调用(通常为 n*ln(n) 次),所以应该有效地实现
the reason you are seeing
compareTo(Object)
is because of Type Erasure. it just means that at runtime the type information is no longer needed for comparing the values.most likely the reason for your slowdown is
1) very, very big TreeSet with lots of elements
2) - more likely - your compareTo method does something expensive. because it is called very often (n*ln(n) times typically ), it should be implemented efficiently
不,在这种情况下您不能强制静态调用。
实例方法可以通过
invokespecial
指令“非虚拟”调用。 当目标在编译时已知时使用此指令,例如构造函数或私有方法。 在其他情况下,即使目标方法是final
,也会使用invokevirtual
或invokeinterface
指令。No, you can't force static invocation in this case.
An instance method can be invoked "non-virtually" by the
invokespecial
instruction. This instruction is used when the target is known at compile time, like a constructor or a private method. In other cases—even when the target method isfinal
—theinvokevirtual
orinvokeinterface
instructions are used.由于 java 在运行时不保留泛型类型,理想情况下,它们的行为应该相同。 可能还有其他原因导致了问题。
Since java does not preserve generic types at runtime, ideally both of them should behave the same. Probably, there is something else which is causing the problem.
您不必猜测这是否属实。
只需暂停几次,您就会立即捕捉到它。
显示完整的调用堆栈,包括对库例程的调用。
我的猜测(可能是错误的)是它正在经历 9 码的 OLE 风格调用 hoo-haw。
You shouldn't have to guess if this is true.
Just pause it a few times, and you will catch it in the act.
Display the call stack in its entirety, including calls into library routines.
My guess (which could be wrong) is that it's going through nine-yards of OLE-style invocation hoo-haw.