keakon
2011-01-07 22:34:54 +08:00
我测试得和你正好相反:
from timeit import Timer
print Timer('''a=None
if a:pass''').timeit(0xffffff)
print Timer('''a=None
if a is None:pass''').timeit(0xffffff)
前者明显快:
0.599301028483
0.708215988345
而且我执行了1千多万次,相差也只有0.1秒左右,很难相信是它造成的性能瓶颈。
再看字节码,前者是:
0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (a)
6 LOAD_FAST 0 (a)
9 JUMP_IF_FALSE 4 (to 16)
后者是:
0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (a)
6 LOAD_FAST 0 (a)
9 LOAD_CONST 0 (None)
12 COMPARE_OP 8 (is)
15 JUMP_IF_FALSE 4 (to 22)
明显前者少执行了2条语句,没有理由更慢