[Python-Dev] String concatenation

Simon Cross hodgestar at gmail.com
Sun Aug 3 20:38:33 CEST 2008


On Sun, Aug 3, 2008 at 8:29 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> In many cases there is no runtime concatenation cost.
>
>>>> def f():
> ...  return "first" + "second"
> ...
>>>> import dis
>>>> dis.dis(f)
>  2           0 LOAD_CONST               3 ('firstsecond')
>              3 RETURN_VALUE

The "many cases" only extends to strings whose combined length is less
than 20 characters:

>>> dis.dis(lambda : "1234567890123456789" + "0")
  1           0 LOAD_CONST               2 ('12345678901234567890')
              3 RETURN_VALUE
>>> dis.dis(lambda : "1234567890123456789" + "01")
  1           0 LOAD_CONST               0 ('1234567890123456789')
              3 LOAD_CONST               1 ('01')
              6 BINARY_ADD
              7 RETURN_VALUE

Adjacent string concentation works on arbitrary length string constants:

>>> dis.dis(lambda : "12345678901234567890"  "12345678901234567890")
  1           0 LOAD_CONST               0
('1234567890123456789012345678901234567890')
              3 RETURN_VALUE


More information about the Python-Dev mailing list