python中变量的名称和程序效率

Vin*_*nce 6 python variables performance

当我编程时,我喜欢给我的变量非常有意义的名字.根据我的理解,在C++和其他编译语言中,这两行是完全等价的:

第1行:

bool a = true;
Run Code Online (Sandbox Code Playgroud)

第2行:

bool bob_likes_very_much_to_eat_strawberry_on_friday_evening = true;
Run Code Online (Sandbox Code Playgroud)

原因是:它将被编译,变量名称在进程中丢失(?).

另一方面,这就是我要问的,似乎以下两个在python中不相同:

第1行:

a = True
Run Code Online (Sandbox Code Playgroud)

第2行:

bob_likes_very_much_to_eat_strawberry_on_friday_evening = True
Run Code Online (Sandbox Code Playgroud)

原因是它被解释了,解释器将使用一些带有变量名的字典作为它将要查询的键(?).我不知道这些字典是如何实现的,但对于我来说,散列长变量名可能需要更长时间(?)并且在某些情况下会产生影响并不是很疯狂.

那么,在某些情况下我应该小心保持我的变量名称长度合理吗?

注1:这个线程非常相似: 你如何命名变量对应用程序的内存使用有什么影响? 但没有关于python出现的明确答案(选择的答案说它一般会对解释语言产生影响,其他答案说它对python没有特别的影响)

注2:我的观点不是提倡由于代码不可读而导致错误的微优化.我想要知道如果通过提供额外的长名称,我在执行速度方面做了某种妥协.

She*_*eng 3

差异应该很小。但我在 Python 2.7.6 with Win7 64 Bit 上得到了一些与第一个答案不同的结果。

>>> import timeit
>>> timeit.timeit(stmt="a = True", number=1000000000)
33.17448742396358
>>> timeit.timeit(stmt="bob_likes_very_much_to_eat_strawberry_on_friday_evening = True", number=1000000000)
32.47728300208675
>>> timeit.timeit(stmt="bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening_bob_likes_very_much_to_eat_strawberry_on_friday_evening = True", number=1000000000)
33.11944278143642
Run Code Online (Sandbox Code Playgroud)

因此,它应该取决于实现和平台。

在内存使用方面,考虑到页对齐,变量名越长,占用的空间也越大。

此外,即使长变量名称也会花费更多的时间和空间。如果它更有意义且易于理解,我一定会使用它。这比效率更重要。