Python常见问题:“异常有多快? [英] Python FAQ: “How fast are exceptions?”

查看:81
本文介绍了Python常见问题:“异常有多快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在看Python的常见问题,因为在另一个问题提到。从来没有真正看过它,我发现这个问题:异常有多快?:

I was just looking at the Python FAQ because it was mentioned in another question. Having never really looked at it in detail before, I came across this question: "How fast are exceptions?":


一个try / except块是非常有效的。实际上捕获异常是昂贵的。在2.0之前的Python版本中,常见的是使用这个成语:

A try/except block is extremely efficient. Actually catching an exception is expensive. In versions of Python prior to 2.0 it was common to use this idiom:

try:
    value = mydict[key]
except KeyError:
    mydict[key] = getvalue(key)
    value = mydict[key]


我对捕获异常是昂贵的部分感到有点惊讶。这仅仅是指除了之外的那些案例,您将实例将例外保存在变量中,或者通常都是,除了包括上面的例子)?

I was a little bit surprised about the "catching an exception is expensive" part. Is this referring only to those except cases where you actually save the exception in a variable, or generally all excepts (including the one in the example above)?

我一直认为使用这样的成语将显示出非常pythonic,特别是在Python 它是更容易要求宽恕而不是获得许可。还有很多关于SO的答案通常遵循这个想法。

I’ve always thought that using such idioms as shown would be very pythonic, especially as in Python "it is Easier to Ask Forgiveness than it is to get Permission". Also many answers on SO generally follow this idea.

是否捕获异常的性能真的很糟糕?在这种情况下,是否应该遵循LBYL(在你飞跃之前)?

Is the performance for catching Exceptions really that bad? Should one rather follow LBYL ("Look before you leap") in such cases?

(请注意,我不直接谈论FAQ中的示例;还有很多其他例子,你只需要注意一个异常,而不是检查以前的类型。)

推荐答案

捕捉异常 是昂贵的,但异常应该是 (读取,不经常发生)。如果异常是罕见的,那么 try / catch 比LBYL快。

Catching exceptions is expensive, but exceptions should be exceptional (read, not happen very often). If exceptions are rare, try/catch is faster than LBYL.

以下示例使用字典键查找例外和LBYL当密钥存在和何时不存在:

The following example times a dictionary key lookup using exceptions and LBYL when the key exists and when it doesn't exist:

import timeit

s = []

s.append('''\
try:
    x = D['key']
except KeyError:
    x = None
''')

s.append('''\
x = D['key'] if 'key' in D else None
''')

s.append('''\
try:
    x = D['xxx']
except KeyError:
    x = None
''')

s.append('''\
x = D['xxx'] if 'xxx' in D else None
''')

for i,c in enumerate(s,1):
    t = timeit.Timer(c,"D={'key':'value'}")
    print('Run',i,'=',min(t.repeat()))



输出



Output

Run 1 = 0.05600167960596991       # try/catch, key exists
Run 2 = 0.08530091918578364       # LBYL, key exists (slower)
Run 3 = 0.3486251291120652        # try/catch, key doesn't exist (MUCH slower)
Run 4 = 0.050621117060586585      # LBYL, key doesn't exist

当通常的情况也不例外, try /与LBYL相比,捕获非常有效。

When the usual case is no exception, try/catch is "extremely efficient" when compared to LBYL.

这篇关于Python常见问题:“异常有多快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆