I had exactly the same problem. It may seem to be elegant to use this apache-commons builder however the compareTo
method can be called a lot and when you have a lot of data it will be called even more.
The objects are pretty light but there are so many generated in the short amount of time that it causes a big GC pressure and bigger pauses eventually giving an impression that the service is stale.
I wanted to come with something that is both reusable and does not allocate any memory and replaced the CompareToBuilder
with the following util:
/**
* Utility for implementing null safe and efficient {@link Comparable#compareTo(Object)}.
*
* Note: it does not use vararg for a performance reason.
*
* @author aleksanderlech
*/
public final class ComparingUtils {
public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>, T3 extends Comparable<T3>> int compare(int upstreamComparision, T1 o1v1, T1 o2v1, T2 o1v2, T2 o2v2, T3 o1v3, T3 o2v3) {
return compare(compare(compare(upstreamComparision, o1v1, o2v1), o1v2, o2v2), o1v3, o2v3);
}
public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> int compare(int upstreamComparision, T1 o1v1, T1 o2v1, T2 o1v2, T2 o2v2) {
return compare(compare(upstreamComparision, o1v1, o2v1), o1v2, o2v2);
}
public static <T1 extends Comparable<T1>> int compare(int upstreamComparision, T1 v1, T1 v2) {
if(upstreamComparision == 0) {
if(v1 == v2) {
return 0;
}
if(v1 == null) {
return 1;
} else if(v2 == null) {
return -1;
}
return v1.compareTo(v2);
}
return upstreamComparision;
}
private ComparingUtils() {}
}
the usage is as follows:
@Override
public int compareTo(Name o) {
return compare(super.compareTo(o), this.english, o.english, this.arabic, o.arabic);
}