简体   繁体   English

变量名称的长度会影响程序运行的速度吗?

[英]Does the length of a variable's name affect the speed the program will run?

I have a short bit of code that needs to run for a long long time.我有一小段代码需要长时间运行。 I am wondering if the length of the variable's names that I use can alter the speed at which the program executes.我想知道我使用的变量名称的长度是否可以改变程序执行的速度。 Here is a very simple example written in Python.这是一个用 Python 编写的非常简单的示例。

Program A程序A

    x = 1
    while not x == 0:
          print('message')

Program B程序B

    xyz = 1
    while not xyz == 0:
          print('message')

Will Program A print 'message' more times than Program B if I run program A and program B for 30 years on two identical machines.如果我在两台相同的机器上运行程序 A 和程序 B 30 年,程序 A 会比程序 B 打印更多次“消息”。

No, the names themselves have no effect on how quickly the resulting code runs.不,名称本身对结果代码的运行速度没有影响。 Variable names are just used to distinguish in the Python source two variables that are represented by integer indices into a lookup table:变量名只是用来区分 Python 源代码中由整数索引表示的两个变量在查找表中:

>>> dis.dis('x=1')
  1           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (x)
              4 LOAD_CONST               1 (None)
              6 RETURN_VALUE
>>> dis.dis('xyz=1')
  1           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (xyz)
              4 LOAD_CONST               1 (None)
              6 RETURN_VALUE
>>> dis.dis('x=1;xyz=2;')
  1           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (x)
              4 LOAD_CONST               1 (2)
              6 STORE_NAME               1 (xyz)
              8 LOAD_CONST               2 (None)
             10 RETURN_VALUE

In the first two, you'll notice no distinction based the variable name is made in the resulting byte code.在前两个中,您会注意到在生成的字节码中没有基于变量名称的区别。 In the last, you'll see that the byte code differentiates between the two, but only on the order in which they are defined, not the length of the label.在最后,您将看到字节码在两者之间进行区分,但仅在定义它们的顺序上,而不是标签的长度上。

The results that @chepner mentioned are correct, Python can take longer to run the code in the console, but once the code is compiled the results are the same. @chepner 提到的结果是正确的,Python 在控制台中运行代码可能需要更长的时间,但是一旦代码被编译,结果是相同的。

To make sure that this is correct, I created the following code also inspired by the answer from @knifer:为了确保这是正确的,我创建了以下代码也受到@knifer 的回答的启发:

from time import time
from numpy import average,std

x                                              = 1
xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk = 1

short_runs = 0
long_runs  = 0

for _ in range(int(2e7)):
    
    t0 = time()
    if x:
        pass
    short_runs += time() - t0
    
    t0 = time()
    if xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk:
        pass
    long_runs  += time() - t0

print('Runtime results:')
print(f"Small variable runs : (sum = {short_runs:.3f})")
print(f"Long  variable runs : (sum = {long_runs :.3f})")

The code I propose is somewhat different, in the sense that the trial runs for the long and the short variable names are intertwined, such that any differences caused by underlying OS processes are minimized.我提出的代码有些不同,因为长变量名和短变量名的试验运行是交织在一起的,这样由底层操作系统进程引起的任何差异都被最小化。

The results of the code vary depending on whether you copy-paste the code into a Python console, or you call the code as a program ( python trial_runs.py ).代码的结果取决于您是copy-paste代码copy-paste到 Python 控制台中,还是将代码作为程序调用 ( python trial_runs.py )。 Runs using copy-paste tend to be slower using long variables names, whereas calling the code as a program yields identical running times.使用长变量名称时,使用copy-paste运行往往会更慢,而将代码作为程序调用会产生相同的运行时间。

PS.附注。 The actual running times change all the time for me (in one direction or the other), so it's hard to report exact values.实际运行时间对我来说一直在变化(在一个方向或另一个方向),因此很难报告确切的值。 Even the long variable names can sometimes run faster, although this is very rare on the Python console.即使是长变量名有时也可以运行得更快,尽管这在 Python 控制台上非常罕见。 The biggest conclusion is that any differences are really small either way :)最大的结论是,无论哪种方式,任何差异都非常小:)

The difference is very small and we cant conclude that is because of name of variable.差异非常小,我们不能得出结论,这是因为变量的名称。

import timeit
x=1
xyz=1


start_time = timeit.default_timer()
for i in range(1,1000000):
    if x==1:
        print("message")
elapsed = timeit.default_timer() - start_time


start_time2 = timeit.default_timer()
for i in range(1,1000000):
    if xyz==1:
        print("message")

elapsed2 = timeit.default_timer() - start_time2

print("small variable printing = ",str(elapsed),"big variable printing = "+str(elapsed2))

And the Result was :结果是:

small variable printing =  3.6490847053481588 big variable printing = 3.7199463989460435

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM