Hacker News new | past | comments | ask | show | jobs | submit login

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].




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: