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 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
comparemethod will be invoked byCollections.sortwhenever it needs to compare two elements of the List to be sorted.