java - Which way of setting something when it is null, is faster? -
which faster in java, , 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 called often, , object
null
first time it's called, don't take cost of thrown npe
into account (it happens once).
p.s. know second better because of simplicity, readability, etc, , i'd surely go in real software. know evil of premature optimization, no need mention it. i'm merely curious these little details.
to answer question, version 1 slower when explodes because creating exceptions quite expensive, not faster version 2 because jvm must null check anyway you're not saving anytime. compiler optimize code it's no faster anyway.
also exceptions should reserved exceptional. initial state of null not exceptional.
use lazy initialization pattern:
someclass getit() { if (it == null) = new someclass(); return it; } ... getit().somemethod();
Comments
Post a Comment