Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a modern JVM optimize simple inline anonymous class allocation?

I got a code review remark today to extract this anonymous class into a field, to avoid allocating it over and over again:

Collections.transform(new Function<Foo, Bar>(){
  Bar apply(Foo foo) {
    // do some simple local transform of foo into a Bar.
  }
});

I replied that "it doesn't matter, the JVM optimizes it". While I know for a fact that this "optimization" won't affect the performance in any way and I think the added value of having the code accessible inline is worth it, I'm curious if I was right about the JVM optimization. So, my question is - it the proposed refactoring absolutely a no-op, because the JVM will optimize it anyway, or is there some minuscule theoretical perf gain here?

like image 311
ripper234 Avatar asked May 24 '11 19:05

ripper234


Video Answer


1 Answers

I wouldn't particularly expect it to optimize that, no.

It would have to make sure that Collections.transform never stashed away the Function, and that the method itself never makes this visible etc. Obviously all that's doable - but it would potentially be quite a lot of work for a relatively small gain in a very few situations.

Now what any particular VM does is hard to say without very careful examination - but I think "It's not going to affect performance significantly" is a more reasonable thing to say than "The JVM optimizes it."

like image 153
Jon Skeet Avatar answered Nov 06 '22 23:11

Jon Skeet