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

python中变量的名称和程序效率,python,variables,performance,Python,Variables,Performance,当我编程时,我喜欢给变量起一个非常有意义的名字。 根据我的理解,在C++和其他编译语言中,这两条线完全等价: 第1行: bool a = true; a = True 第2行: bool bob_likes_very_much_to_eat_strawberry_on_friday_evening = true; bob_likes_very_much_to_eat_strawberry_on_friday_evening = True 原因是:它将被编译,并且变量名在过程中丢失(?)

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

第1行:

bool a = true;
a = True
第2行:

bool bob_likes_very_much_to_eat_strawberry_on_friday_evening = true;
bob_likes_very_much_to_eat_strawberry_on_friday_evening = True
原因是:它将被编译,并且变量名在过程中丢失(?)

另一方面,这也是我要问的,在python中,以下两个似乎是不等价的:

第1行:

bool a = true;
a = True
第2行:

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

所以,在某些情况下,我应该注意保持变量名的长度合理吗

注1: 此线程非常相似: 但关于python并没有明确的答案(选定的答案说它对一般解释语言有影响,其他答案说它对python并没有特别的影响)

注2: 我的观点不是提倡错误的微观优化,这是不可读代码的结果。我想知道,通过给出超长名称,我是否在执行速度上做了某种妥协

import timeit

a = timeit.Timer(stmt="a = 0")
a.repeat()

# => [0.025734134655067464, 0.025691468425065977, 0.025745867864316097]

b = timeit.Timer(stmt="bob_likes_very_much_to_eat_strawberry_on_friday_evening = 0")
b.repeat()
# => [0.025780711948755197, 0.025762934357771883, 0.02595848789496813]
。。。长变量名似乎慢了约0.2%


它还将使用额外的30字节左右的内存。

差异应该非常小。但是我在使用Win7 64位的Python2.7.6上得到了与第一个答案不同的结果

>>> 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
因此,它应该是基于实现和平台的

在内存使用方面,考虑到页面对齐,更长的变量名应该占用更多的空间

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