Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
} 
like image 750
Roxana Avatar asked Jun 13 '14 07:06

Roxana


People also ask

Is try except faster than if?

Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.

Is try except slower than if?

If you don't raise an exception your code will be faster with try except, otherwise it takes a little bit more time to treat the exception. In other word, if you are sure that your exception is extraodinary (it happens only in exceptional cases) it's cheaper for you to use try-except.

Why is exception better than assertion?

The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.

Which is faster try catch or if-else?

If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.


1 Answers

if definitely.

Throwing an exception is a costly operation and this is not the purpose of Exception.

The purpose of Exception is to catch exceptional condition that may arise at runtime but you shouldn't code to generate exception to make that decision.

like image 54
jmj Avatar answered Sep 23 '22 00:09

jmj