Does some preliminary delay compare?

I just found this statement: "You can significantly increase compareTo performance by first comparing items that are likely to be different." It's true? And if so, why?

+4
source share
3 answers

Consider a class with several properties. To compare instances you need to compare some of their properties. If all properties except one are equal, then the number of comparisons you need to perform depends on the order of the property comparisons: if you first compare different properties, you get the result with one comparison. But if you were comparing different properties in the past, you had to make n comparisons to get the same result.

As @Kdeveloper noted, the performance difference may not be noticeable if you do not do many such comparisons in batches. But another advantage is the logical ordering of IMHO: it makes you think about the logical relationship between the properties of the class. In general, since it is an optimization without interruption (i.e., it does not make the code more difficult to read and maintain), I think it is worth doing most of the time.

+5
source

Yes it's true

Because, if you first make the most selective comparison, on average you will execute less code for each comparison. But since these tests are usually very fast, speed improvements will be noticeable only when comparing many objects, for example, when sorting a large collection.

+1
source

It's true? And if so, why?

Well, literally, no. The compareTo method will execute equally long, regardless of history.

If he can get any overall performance in a particular implementation? Yes exactly. But in order to be able to answer your question, we need more context about the situation.

0
source

Source: https://habr.com/ru/post/1341646/


All Articles