pythonperformancenaming-conventionsnaming-containers

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.

Program A

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

Program 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.


Solution

  • 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:

    >>> 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.