Member-only story
Effective Java! Avoid Creating Unnecessary Objects!
Today we are onto our sixth item from Effective Java. This one’s title particularly makes me smile. Avoid creating unnecessary objects. What’s more uncontroversial than saying, “Don’t do things you don’t need to do.” We are all looking for shortcuts of how to get a job done more quickly so this one we automatically get for free right? Well not quite, there is actually a little bit more to be said here than, “Be lazy.” So let’s get started.
So why would someone do something that they don’t need to do? Well we will go over some of the ways this can happen throughout this post but I would sum up most of these cases simply as the following, ignorance and lack of attention. This is understandable. Sometimes we just don’t realize the damage we may be doing or we do know to avoid something but may not realize we are doing that thing.
Let’s start off with the first example from the book:
String title = new String("Effective Java");
So what does this do? Well it does exactly what it looks like it will do, it creates a new String for each time it is called. But that’s not what we actually want to do. This simply creates more objects for the garbage collector to clean up without any benefit. Compare that to the more efficient way to accomplish this which also turns out to be cleaner:
String title = "Effective Java";
In this case no extra objects will be created no matter how many times this line is run…