Bug or feature: double strings as one

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Aug 7 23:31:31 EDT 2009


On Fri, 07 Aug 2009 17:35:28 +0000, kj wrote:

> I fail to see why
> 
> x = ("first part of a very long string "
>      "second part of a very long string")

That's done by the compiler at compile time and is fast.

> is so much better than
> 
> x = ("first part of a very long string " +
>      "second part of a very long string")

That's done by the Python virtual machine at runtime and creates two 
strings, then passes them to a method, which creates a third string, then 
(usually) disposes of the first two strings.

Except for some versions of the CPython implementation, which has a 
keyhole compiler which folds constants at runtime. But it's a simple 
optimizer, easy to defeat:

>>> import dis
>>> dis.dis(compile("s = ''; s + 'a' + 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('a')
             12 BINARY_ADD
             13 LOAD_CONST               2 ('b')
             16 BINARY_ADD
             17 POP_TOP
             18 LOAD_CONST               3 (None)
             21 RETURN_VALUE
>>>
>>> dis.dis(compile("s = ''; s + 'a' 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('ab')
             12 BINARY_ADD
             13 POP_TOP
             14 LOAD_CONST               2 (None)
             17 RETURN_VALUE



-- 
Steven



More information about the Python-list mailing list