改进可比性 比较性能

发布于 2024-07-15 00:23:26 字数 420 浏览 7 评论 0原文

我分析了我的代码,发现我的类(实现了 Comparable)花费的 cpu 时间比我假设的 8 倍多,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

辞慾 2024-07-22 00:23:26

您看到 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

盛夏已如深秋| 2024-07-22 00:23:26

不,在这种情况下您不能强制静态调用。

实例方法可以通过 invokespecial 指令“非虚拟”调用。 当目标在编译时已知时使用此指令,例如构造函数或私有方法。 在其他情况下,即使目标方法是 final,也会使用 invokevirtualinvokeinterface 指令。

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 is final—the invokevirtual or invokeinterface instructions are used.

轻许诺言 2024-07-22 00:23:26

由于 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.

蝶舞 2024-07-22 00:23:26

我认为速度放缓是因为
为此进行虚拟表查找
方法。

您不必猜测这是否属实。
只需暂停几次,您就会立即捕捉到它。
显示完整的调用堆栈,包括对库例程的调用。

我的猜测(可能是错误的)是它正在经历 9 码的 OLE 风格调用 hoo-haw。

I assume that the slowdown is because
of virtual table lookup for this
method.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文