Normally I prefer null check. But in current scenario I know that most of the time my if condition will pass and there are few legitimate scenario where object may be null.
Also, load is huge (about 5 million calls / hour)
Now I trying to find which way is better from performance perspective. Already checked try/catch vs null check in java but my case is unique.
Also checked Which is faster, try catch or if-else in java (WRT performance) but both this one and above ones are in generic context where knowledge of pass/fail ratio is not available.
public void process(Job job) {
//... some code which processes job
SubJob subJob = job.getSubJob();
if(subJob != null) { // 99% of the time this will pass
//.. do something
}
}
try/catch version
public void process(Job job) {
//... some code which processes job
SubJob subJob = job.getSubJob();
try {
//.. do something
}catch(NullPointerException e) { //This may occure only 1% of the time.
//...
}
}
Update:
Winner is null check. In Try/catch, internally JVM will do null check and throw NPE anyway and on top of that exception handling in JVM (creation of stack etc) will be overhead. Also as per another answer, modern CPUs are intelligent enough to handle these scenario with good prediction which in my unique case will always work in favor.
I also wrote program (posted below under my name) and results are clearly indicating that null check is way better on my AMD processor.
Thank you folks for guiding me.