Does the JDK compiler optimize the use of anonymous classes without instance variables?

I was curious, I see a lot of things:

Arrays.sort(array, new Comparator<Integer>() {
    public int compare(Integer a, Integer b) {
        return Math.abs(a) < Math.abs(b);
    }
});

since the anonymous class created here does not have instance variables, is the standard JDK compiler smart enough to only have one instance of this anonymous class and reuse it? Or is it desirable to instantiate this anonymous class in a static field and always pass a static Comparator object?

The UPDATE . When I say "JDK compiler", I also mean the JIT part. The above is also just an example. I was very interested if, as a best practice, I would create static fields for the above, instead of embedding anonymous class instances. In some cases, the issue of using performance / resource will be minor. But other cases may not be ...

+5
source share
5 answers

javac will definitely not do this; which violates the semantics of the language. The JVM can optimize it in theory, but it is still not so smart. Static would be faster.

, javac, , , - new, javac new.

, - java 8 ,

Arrays.sort(array, (Integer a,Integer b) => Math.abs(a)<Math.abs(b) )

javac , , .

+3

.

javac -, . , , , . JVM , MIGHT - - .

, , .

+1

javap, ; , . , , ( ), .

0

, javac. , javac -, . , hotspot . , ( Math.abs()).

0

. . , Integer , Integer, . , .

0

All Articles