Which is faster in Java, and why?
try {
object.doSomething()
} catch (NullPointerException e) {
if (object == null) {
object = new .....;
object.doSomething();
} else throw e;
}
or
if (object == null) {
object = new .....;
}
object.doSomething();
and why?
The code would be called often, and object is only null the first time it’s called, so don’t take the cost of the thrown NPEinto account (it only happens once).
P.S. I know the second is better because of simplicity, readability, etc, and I’d surely go for that in real software. I know all about the evil of premature optimization, no need to mention it.
I’m merely curious about these little details.
To answer your question, version 1 is much slower when it explodes because creating Exceptions is quite expensive, but it is not faster than version 2 because the JVM must do the null check itself anyway so you’re not saving anytime. The compiler is likely to optimize the code so it’s no faster anyway.
Also Exceptions should be reserved for the exceptional. Initial state of null is not exceptional.
Use the lazy initialization pattern: