Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if vs try-except

Tags:

I was wondering why the try-except is slower than the if in the program below.

def tryway():     try:         while True:             alist.pop()     except IndexError:         pass  def ifway():     while True:         if alist == []:              break         else:             alist.pop() if __name__=='__main__':     from timeit import Timer     alist = range(1000)     print "Testing Try"     tr = Timer("tryway()","from __main__ import tryway")     print tr.timeit()     print "Testing If"     ir = Timer("ifway()","from __main__ import ifway")     print ir.timeit() 

The results I get are interesting.

Testing Try 2.91111302376 Testing If 0.30621099472 

Can anyone shed some light why the try is so much slower?

like image 515
James Avatar asked Oct 14 '10 03:10

James


People also ask

Is try-except faster than if Python?

Let's consider our above example, if we expect that 99% of the cases the values of 'value' will not be equal to 0, we can use try/except approach. It will be faster if the exception really is exceptional. If the possibility of value becomes 0 is more than 50 %, then using 'if' is probably better.

What is the difference between try-Except And if else in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

Is if else same as try-except?

Summary. Use the Python try... except...else statement provides you with a way to control the flow of the program in case of exceptions. The else clause executes if no exception occurs in the try clause.

Can we use if in TRY-except Python?

How try() works? First, the try clause is executed i.e. the code between try and except clause. If there is no exception, then only the try clause will run, except the clause is finished.


2 Answers

You're setting alist only once. The first call to "tryway" clears it, then every successive call does nothing.

def tryway():     alist = range(1000)     try:         while True:             alist.pop()     except IndexError:         pass  def ifway():     alist = range(1000)     while True:         if alist == []:             break         else:             alist.pop() if __name__=='__main__':     from timeit import Timer     print "Testing Try"     tr = Timer("tryway()","from __main__ import tryway")     print tr.timeit(10000)     print "Testing If"     ir = Timer("ifway()","from __main__ import ifway")     print ir.timeit(10000)  >>> Testing Try >>> 2.09539294243 >>> Testing If >>> 2.84440898895 
like image 126
Glenn Maynard Avatar answered Nov 23 '22 10:11

Glenn Maynard


Exception handling is generally slow in most languages. Most compilers, interpreters and VMs (that support exception handling) treat exceptions (the language idiom) as exceptions (uncommon). Performance optimization involves trade-offs and making exceptions fast would typically mean other areas of the language would suffer (either in performance or simplicity of design).

At a more technical level, exceptions generally mean that the VM/interpretter (or the runtime execution library) has to save a bunch of state and begin pulling off all the state on the function call stack (called unwinding) up until the point where a valid catch (except) is found.

Or looking at it from a different viewpoint, the program stops running when an exception occurs and a "debugger" takes over. This debugger searches back through the stack (calling function data) for a catch that matches the exception. If it finds one, it cleans things up and returns control to the program at that point. If it doesn't find one then it returns control to the user (perhaps in the form of an interactive debugger or python REPL).

like image 28
kanaka Avatar answered Nov 23 '22 08:11

kanaka