对列表进行排序时,内联使用Java Comparator(带有匿名内部类)与实现单独的自定义Comparator类之间在性能上有什么区别吗?

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());
    }
});

另外,何时会调用compare()方法?

最佳答案

还有选项3-lambda Function:

Collections.sort(list, (a, b) -> a.getErrorCode().compareTo(b.getErrorCode()));

根据this benchmark data,它应该快大约2倍。

...或(由于@JB Nizet)选项4:
list.sort(Comparator.comparing(WorkflowError::getErrorCode))

07-27 20:10