Is repeatedly instantiating an anonymous class wasteful?

后端 未结 3 719
借酒劲吻你
借酒劲吻你 2021-02-14 02:32

I had a remark about a piece of code in the style of:

Iterable upperCaseNames = Iterables.transform(
    lowerCaseNames, new Function

        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 02:45

    Found this thread: Java anonymous class efficiency implications , you may find it interesting

    Did some micro-benchmarking. The micro-benchmark was a comparison between: instantiating an (static inner) class per loop iteration, instantiating a (static inner) class once and using it in the loop, and the two similar ones but with anonymous classes. For the micro benchmarking the compiler seemed to extract the anonymous class out of loops and as predicted, promoted the anonymous class to an inner class of the caller. This meant all four methods were indistinguishable in speed. I also compared it to an outside class and again, same speed. The one with anonymous classes probably took ~128 bits of space more

    You can check out my micro-benchmark at http://jdmaguire.ca/Code/Comparing.java & http://jdmaguire.ca/Code/OutsideComp.java. I ran this on various values for wordLen, sortTimes, and listLen. As well, the JVM is slow to warm-up so I shuffled the method calls around. Please don't judge me for the awful non-commented code. I program better than that in RL. And Microbenching marking is almost as evil and useless as premature optimization.

提交回复
热议问题