Should comparators be instantiated every time or just once?
comparator, java
Solution
If the comparator has no state (and most won't) then it's absolutely fine to create a single instance and use that everywhere. Don't create extra objects just for the sake of it.
Problem
With a custom comparator, are there any advantages to instantiating it every time instead of creating it as a constant (using anonymous class) and using that single instance? I've always thought that there's no advantage to creating a new instance every time and had always gone the way of option #2 (single instance in static final field). ``` public class SomeClass { //First option: private static class SomeCustomComparator implements Comparator<SomeObject> { public int compare(SomeObject o1, SomeObject o2) { /*implementation*/ } } //Second option: private static final Comparator<SomeObject> CUSTOM_COMPARATOR = new Comparator<SomeObject> { public int compare(SomeObject o1, SomeObject o2) { /*implementation*/ } }; public void doSomething() { //are there any advantages to one over the other? SortedSet<SomeObject> s1 = new TreeSet<>(CUSTOM_COMPARATOR); SortedSet<SomeObject> s2 = new TreeSet<>(new SomeCustomComparator()); } } ``` The assumption here is that no state needs to be kept in the comparator. What if doSomething() gets called a lot? What if doSomething() gets called from multiple threads? What if CUSTOM_COMPARATOR were to be pulled out into a common class and made public instead of private?