Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDK compiler optimize use of anonymous classes with no instance variables?

I was curious, I see this kind of thing a lot:

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 has no instance variables, is the standard JDK compiler smart enough to only instantiate that anonymous class once and reuse it? Or is it advisable to instantiate that anonymous class in a static field and always pass the static Comparator object?

UPDATE: When I say "JDK compiler", I mean the JIT portion too. The above is also just an example. I was really curious if I should, as a best practice, create static fields for the above instead of inlining anonymous class instantiations. In some cases the performance/resource usage issue will be negligible. But other cases might not be...

like image 503
at. Avatar asked Oct 10 '22 23:10

at.


1 Answers

javac will definitely not do such thing; that would violate the language semantics. JVM could optimize it in theory, but it's not that smart yet. A static one would be faster.

Ironically, such analysis and optimization would be easy for javac, and it can be done today, except it's forbidden to do so - the source says new, so javac must new.

Rumor has it that the coming lambda expression in java 8 will make an effort on this issue, in

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

javac is required to analyze that the lambda is stateless, and a lazily created single instance is enough, and that's what it must compile the code into.

like image 105
irreputable Avatar answered Oct 20 '22 05:10

irreputable