When sorting a list, is there any performance difference between using a java Comparator in-line (with an anonymous inner class) vs implementing a separate custom Comparator class?
1.
public class SortByErrorComparator implements Comparator<WorkflowError> {
public int compare(WorkflowError obj1, WorkflowError obj2) {
return obj1.getErrorCode().compareTo(obj2.getErrorCode());
}
}
Collections.sort(list, new SortByErrorComparator()) ;
2.
Collections.sort(list, new Comparator<WorkflowError>() {
public int compare(WorkflowError obj1, WorkflowError obj2) {
return obj1.getErrorCode().compareTo(obj2.getErrorCode());
}
});
Also, when will the compare()
method be invoked?
There's also option 3 - a lambda
Function
:which should be about 2 x faster, according to this benchmark data.
... or (thanks to @JB Nizet) option 4:
There's shouldn't be any performance difference between the two variations, since anonymous classes should produce identical byte code as regular classes (assuming they have the same source code). The only difference is that they'll have a generated name.
The
compare
method will be invoked byCollections.sort
whenever it needs to compare two elements of the List to be sorted.I made a little test and found no difference (just in some small run the inline comparator shows a slightly better performace). This is the code used to make the test:
Comparator class:
and the output is:
If you have several invocation to the comparator keeping an instance of it would be helpful