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?
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With