简体   繁体   中英

anonymous-inner-classes vs static field

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM