Is try-except slow?

Robert Kern robert.kern at gmail.com
Wed Sep 3 15:47:13 EDT 2008


Steven D'Aprano wrote:
> On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote:
> 
>> ssecorp wrote:
>>> or why does this take so god damn long time?
>> Several reasons. One of which is that try: except: is slow.
> 
> 
> I beg to differ. Setting up a try...except block is very fast. Here's an 
> example in Python 2.5:
> 
> 
>>>> from timeit import Timer
>>>> Timer('len("abc")').repeat()
> [0.27346706390380859, 0.1530919075012207, 0.14886784553527832]
>>>> Timer('''try:
> ...     len("abc")
> ... except:
> ...     pass
> ... ''').repeat()
> [0.27847194671630859, 0.19191384315490723, 0.19077491760253906]
> 
> The difference (approx 0.04 microseconds) applicable to setting up the 
> try...except block is trivial, of the same magnitude as a pass statement:
> 
>>>> Timer('pass').repeat()
> [0.059719085693359375, 0.060056924819946289, 0.059512138366699219]
> 
> 
> However, *catching* the exception may be relatively slow:
> 
>>>> Timer('''try:
> ...     len(abc)  # raise a NameError
> ... except:
> ...     pass
> ... ''').repeat()
> [3.2067418098449707, 2.7088210582733154, 1.9558219909667969]

You're right. My mistake. I was misremembering Guido's old essay about try: 
except: versus if: else:.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list