Hacker News new | ask | show | jobs
by jmlane 5180 days ago
Out of curiosity, in a situation where you are doing negligible condition testing, is try–except still considered "more performant" than if–else flow control? For some reason (and I'm going to do so reading to get clarity on this point), I have had the silly notion that throwing and handling exceptions can be costly.
1 comments

I don't think the try-except is 'more performant'. At least from the below benchmark test it doesn't seem to be so.

  >>> from timeit import timeit
  >>> timeit(setup='x=dict([(i,i*2) for i in range(10)])',stmt=
       """
          if 20 in x:
             pass""")

  0.07420943164572691

  >>> timeit(setup='x=dict([(i,i*2) for i in range(10)])',
       stmt="""
               try:
		  x[20]
               except KeyError:
		  pass""")

  1.1514457843105674
I am on my phone and cannot test this, but the try:except: construct is optimised for the non-exceptional path. The latter is probably faster for x[0] than x[20].