Java Object Creation is Very Fast

I was recently doing a code review and suggested some refactoring to extract some behaviour into separate classes. A common question came up, “This code has to be fast so shouldn’t I avoid object creation?” My instinct is always no, ignore those considerations when coding, let the compiler handle it until proven that you have to step-in. This time I avoided my laziness and cross checked that instinct.

The top result on a quick search said that object creation should be avoided due to expense, but mentioned a Pentium II so I was suspicious. I’m not going to link to that article because I don’t want to signal boost it anymore. The second article had some data that confirmed my instinct. In some cases object creation cost is zero because the compiler can inline them if they don’t escape method scope. Even if they do escape costs are measured in small single or very low double digit nanoseconds. Don’t worry about it when designing your code, only worry about it if you’ve eliminated other expensive parts. Focus on making your code understandable.

Here’s the article that I want to signal boost https://www.bettercodebytes.com/the-cost-of-object-creation-in-java-including-garbage-collection/.

Leave a Reply

Your email address will not be published. Required fields are marked *