CompareTo 是否有某种预启动延迟?

发布于 2024-10-19 13:46:45 字数 71 浏览 2 评论 0原文

我刚刚发现这样的说法:“通过首先比较最有可能不同的项目,可以大大提高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 技术交流群。

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

发布评论

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

评论(3

仄言 2024-10-26 13:46:45

考虑一个具有多个属性的类。为了比较实例,您需要比较它们的一些属性。如果除一个属性之外的所有属性都相等,则需要执行的比较次数取决于属性比较的顺序:如果您碰巧首先比较不同的属性,则只需一次比较即可得到结果。但是,如果您最后比较不同的属性,则必须进行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.

月牙弯弯 2024-10-26 13:46:45

是的,这是真的

因为如果您将最具选择性的比较放在第一位,那么平均来说每次比较执行的代码会更少。但由于这些测试通常非常快,因此只有在比较许多对象时(例如对大集合进行排序时),速度的提高才会明显。

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.

┼── 2024-10-26 13:46:45

这是真的吗?如果是,为什么?

嗯,从字面上来说,不是。无论历史记录如何,compareTo 方法都将花费同样长的时间来执行。

在特定的实现中是否可以获得任何总体性能?是的,当然。但为了能够回答你的问题,我们需要更多有关情况的背景信息。

Is it true? And if it is, why?

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.

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