java - What are the tradeoffs for different approaches when creating a comparator? -
suppose have record
class string name
(could other type) attribute. in class have method order(list<record>)
needs sort list name
. this, want create custom stateless comparator
. have seen 3 options commonly used:
static comparator
private static final comparator<record> static_comparator = new staticcomparator(); private static class staticcomparator implements comparator<record> { @override public int compare(record m1, record m2) { return m1.getname().compareto(m2.getname()); } } void order(list<record> records) { records.sort(static_comparator); }
singleton comparator
private static enum singletoncomparator implements comparator<record> { instance; @override public int compare(record m1, record m2) { return m1.getname().compareto(m2.getname()); } } void order(list<record> records) { records.sort(singletoncomparator.instance); }
use
comparator.comparing()
void order(list<record> records) { records.sort(comparator.comparing(record::getname)); }
assuming order()
gets called lot, tradeoffs each approach? how compare on matters such serialization, thread safety, , performance?