简体   繁体   中英

Fastest way to compare 2 large objects in java

I want to know what would be the fastest way to compare 2 objects in java 8. I have 2 objects of the same class with 100 properties.

What is the fastest way to find the properties which have different values apart from the compareTo() method in which they are checked for the properties one by one.

You may optimize the equals method so that it bails out as soon difference is found.

If the object is immutable, you may cache its hashCode value, compare the hash value as the first step in the equals method

Another way to optimize would be to pick out some of the equals checks that will most likely return false and separate them from all others. This would give the JIT compiler a chance to inline the fast track. Note that this will only improve performance when the equals method is called often enough to get compiled and the fast track is actually inlined. Later depends on its size and also other factors. So there will be no guarantee and you would need to verify and experiment a bit with a microbenchmark tool like JMH .

Having all the comparisons in one method reduces the likeliness of inlining, since the whole method with 100 comparisons is most likely too big for inlining. JIT compiler's profiling works on method level, so either a complete mehtod gets inlined or it does not get inlined.

Note that this is already advanced micro-optimization. Do this only when your comparison is used frequently and there is a real need for optimization. I used this approach successfully in in one of my projects, where we had a high load scenario with tight time constraints. We did this only because we ran out of other possible optimizations. So think twice, whether you really want to optimize here.

Example:

public boolean equals(Object other) {

  // fast track that may get inlined as long as it is 
  // not too big
  if (!equalsFast(other)) {
    return false;
  }
  // slow track that will not be inlined but only 
  // called sometimes
  return equalsOthers(other);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM