开发者

Does compareTo have some sort of pre-launching delay?

I just found this statement: "One can greatly increase the perform开发者_开发问答ance of compareTo by comparing first on items which are most likely to differ". Is it true? And if it is, why?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜