
捕获异常 非常 昂贵,但是异常应该是 例外的 (读取,不经常发生)。如果例外情况很少,
try/catch则比LBYL要快。
下面的示例在密钥存在和不存在时使用异常和LBYL对字典密钥进行计时:
import timeits = []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()))输出量Run 1 = 0.05600167960596991 # try/catch, key existsRun 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/catch时,与LBYL相比是“极其有效”的。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)