But what is performance ?
- Compare short list of strings with comparator defined as class
- Compare short list of strings with comparator defined as anonymous class
- Compare short list of strings with comparator defined as lambda
- 47563
- 78857
- 111320
And here is code:
package com.company; import java.util.*; public class Main { public static void main(String[] args) { CompareByClass(); CompareByLambda(); CompareByAnonymous(); } private static void CompareByClass() { List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Date timeStart = new Date(); for(int i=0; i<Integer.MAX_VALUE;i++) { Collections.sort(names, new myComparator()); } Date timeStop = new Date(); System.out.println(timeStop.getTime() - timeStart.getTime()); } private static void CompareByAnonymous() { List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Date timeStart = new Date(); for(int i=0; i<Integer.MAX_VALUE;i++) { Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } }); } Date timeStop = new Date(); System.out.println(timeStop.getTime() - timeStart.getTime()); } private static void CompareByLambda() { List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Date timeStart = new Date(); for(int i=0; i<Integer.MAX_VALUE;i++) { Collections.sort(names, (String a, String b) -> b.compareTo(a)); } Date timeStop = new Date(); System.out.println(timeStop.getTime() - timeStart.getTime()); } } package com.company; import java.util.Comparator; public class myComparator implements Comparator<String> { public int compare(String a, String b) { return b.compareTo(a); } }