Python 3.5,使用声明的变量比直接使用它的值要慢?

时间:2016-04-10 05:04:51

标签: python variables

选项1:

b = 1
for i in range(1000000):
    a = b in {1, 2, 3, 4, 5}

选项2:

b = 1
c = {1, 2, 3, 4, 5}
for i in range(1000000):
    a = b in c

选项1比选项2快,我认为Option2应该更快。这与堆栈或堆有什么关系吗?或者这是关于python如何优化其循环?或者是字典命名空间相关吗?

我问这个是因为通常选项2,较慢的版本,是一种更好的编码实践。选项1太硬编码了。

1 个答案:

答案 0 :(得分:1)

没有明显的区别,很可能是因为缓存了结果和其他编译时优化。

但是你把最慢跑的结果视为重要(可能是它们?),似乎第二次跑的最慢跑比第一次慢3到4倍。 (也许这是在任何缓存和优化之前的真正执行速度?IDK)

第一个:

%%timeit
def f1(b, c):
    for i in range(1000000):
        a = b in c

<强>结果:

The slowest run took 30.16 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 123 ns per loop

第二个:

%%timeit
def f2(b):
    for i in range(1000000):
        a = b in {1, 2, 3, 4, 5}

<强>结果:

The slowest run took 8.05 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 126 ns per loop

ipython 3.4.4,anaconda,在Jupyter笔记本中,在一个古老的macbook air上