Check if variable null before assign to null?

Albert picture Albert · Feb 24, 2009 · Viewed 10.6k times · Source

Is variable assignment expensive compared to a null check? For example, is it worth checking that foo is not null before assigning it null?

if (foo != null) {
     foo = null;
}

Or is this worrying about nothing?

Answer

Mike Douglas picture Mike Douglas · Feb 24, 2009

This is a micro-micro-optimization (and possibly something handled by the compiler anyways). Don't worry about it. You'll get a far greater return by focusing on your programs actual algorithm.

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. -- Donald Knuth