CompareTo 是否有某种预启动延迟?
我刚刚发现这样的说法:“通过首先比较最有可能不同的项目,可以大大提高compareTo的性能”。这是真的吗?如果是的话,为什么?
I just found this statement: "One can greatly increase the performance of compareTo by comparing first on items which are most likely to differ". Is it true? And if it is, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑一个具有多个属性的类。为了比较实例,您需要比较它们的一些属性。如果除一个属性之外的所有属性都相等,则需要执行的比较次数取决于属性比较的顺序:如果您碰巧首先比较不同的属性,则只需一次比较即可得到结果。但是,如果您最后比较不同的属性,则必须进行n次比较才能获得相同的结果。
正如 @Kdeveloper 指出的,除非您批量进行大量类似的比较,否则性能差异可能并不明显。但另一个好处是恕我直言逻辑排序:这让您思考类属性之间的逻辑关系。总的来说,由于这是一种非破坏性的优化(即它不会使代码更难以阅读和维护),因此我认为大多数时候都值得这样做。
Consider a class with several properties. For comparing instances, you need to compare some of their properties. If all properties except one are equal, the amount of comparisons you need to do depends on the order of the property comparisons: if you happen to compare the differing properties first, you got the result with one comparison. But if you compare the differing properties last, you had to do n comparisons to get the same result.
As @Kdeveloper noted, the performance difference may not be noticeable unless you do lots of similar comparisons in batches. But the other benefit is IMHO logical ordering: this makes you think about the logical relationship between class properties. And overall, since this is a nondisruptive optimization (i.e. it does not make the code more difficult to read and maintain), I think it is worth doing it most of the time.
是的,这是真的
因为如果您将最具选择性的比较放在第一位,那么平均来说每次比较执行的代码会更少。但由于这些测试通常非常快,因此只有在比较许多对象时(例如对大集合进行排序时),速度的提高才会明显。
Yes, it's true
Because if you put the most selective comparison first, you will on average execute less code for each comparison. But as these test are typically very fast, the speed improvements will only be noticeable if you compare many objects, for example when you sort a big collection.
嗯,从字面上来说,不是。无论历史记录如何,compareTo 方法都将花费同样长的时间来执行。
在特定的实现中是否可以获得任何总体性能?是的,当然。但为了能够回答你的问题,我们需要更多有关情况的背景信息。
Well, literally speaking, no. The
compareTo
method will take equally long time to execute, regardless of history.If it can gain any overall performance in a particular implementation? Yes, for sure. But to be able to answer your question we would need more context about the situation.