0

I prefer to use static field for instances of classes that not store his state in fields instead anonymous-inner-classes. I think this good practice for to less memory and GC usage if method sort(or other) call very often. But my colleague prefer to use anonymous-inner-classes for this case saying that JIT will optimize it.

class MyClass {
    //non fields of class

    /*access modifier*/ final static Comparator<MyClass> comparator = new Comparator<MyClass>(){
        public compare(MyClass o1, MyClass o2){
            //comparing logic
        }
    }
}

Usage example (I prefer):

List<MyClass> list = ...;
Collection.sort(list, MyClass.comparator);

Usage example (my colleague prefer):

List<MyClass> list = ...;
Collection.sort(list, new Comparator<MyClass>(){
    public compare(MyClass o1, MyClass o2){
        //comparing logic
    }
});

1. Using anonymous-inner-classes in openJDK optimized?
2. Please, tell me good practice for this case.

Sergey Morozov
  • 4,528
  • 3
  • 25
  • 39
  • A nitpick: your own example doesn't really make sense. Since `MyClass` has only a single ordering, and it knows about it, it should just implement `Comparable`, rather than having a static field `comparator` of type `Comparator`. – ruakh Dec 25 '13 at 08:26
  • 1
    Your question is really - "anonymous-inner-classes vs named classes". And my answer would be that anonymous-inner-classes are made to make code writing faster and easier, but you should always use the more readable-reusable named-classes when possible. – Elist Dec 25 '13 at 08:27
  • @ruakh It hypothetical example. Instead of Comparator might be other class. – Sergey Morozov Dec 25 '13 at 08:38

1 Answers1

2

I think this good practice for to less memory and GC usage if method sort(or other) call very often.

Well it's the other way round. If you are bothered about memory, the static fields will be there in memory until the class is unloaded.

However, the concern is more of readability here rather than memory or performance. If you find yourself using a Comparator instance may be 2-3 times, or more, it's better to store that in a field, to avoid repeating the code. Even better, mark the field final. If you are going to use it only once, there is no point of it being stored as static field.

But my colleague prefer to use anonymous-inner-classes for this case saying that JIT will optimize it.

I don't understand what kind of optimization is your colleague talking about. You should ask him/her for further clarification. IMO, this is just a pre-mature optimization, and you should really not be bothered.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525