Search code examples
javaexceptionexecution-time

What is more time optimal: if or exception


What costs for sure less time for execution between the two options:

A:

if(something!=null){
    ...
}else{
    //log
}

or:

B:

try{
    something.getField();...
}catch(Exception e){
    //log
} 

Solution

  • Without even having to benchmark: Exception are ALWAYS way more expensive than programming defensively and using ifs as null-guard etc. Exceptions are always more expensive (several orders of magnitude), because the stack trace has to be generated.

    Relevant SO question with benchmark: How slow are Java exceptions?