python何时编译常量字符串字母,以将字符串组合成单个常量字符串?

2024-04-26 03:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

比如

In [9]: dis.disassemble(compile("s = '123' + '456'", "<execfile>", "exec"))
  1           0 LOAD_CONST               3 ('123456')
              3 STORE_NAME               0 (s)
              6 LOAD_CONST               2 (None)
              9 RETURN_VALUE 

我想知道,python何时将常量字符串组合为CONST。 如果可能的话,请告诉我在cpython(无论是2.x还是3.x)的哪些源代码


Tags: store字符串nameinnonereturnvalueload
2条回答

@Raymond Hetting's answer很好,投赞成票(我投了)。我会将此作为注释,但您不能在注释中格式化代码

如果超过20个字符的限制,则反汇编如下所示:

>>> dis.disassemble(compile("s = '1234567890' + '09876543210'", "<execfile>", "exec"))
  1  0 LOAD_CONST  0 ('1234567890')
     3 LOAD_CONST  1 ('09876543210')
     6 BINARY_ADD
     7 STORE_NAME  0 (s)

但是,如果您有两个字符串文本,请记住您可以省去+而使用String literal concatenation来避免二进制添加(即使组合字符串长度大于20):

>>> dis.disassemble(compile("s = '1234567890' '09876543210'", "<execfile>", "exec"))
  1  0 LOAD_CONST  0 ('123456789009876543210')
     3 STORE_NAME  0 (s)

只要组合字符串为20个字符或更少,就会发生这种情况

优化发生在窥视孔优化器中。请参见Python/peephole.chttp://hg.python.org/cpython/file/cd87afe18ff8/Python/peephole.c#l149fold_binops_on_constants()函数的第219行

相关问题 更多 >