In python, why is s * 3 faster than s + s + s?

I was going through the intro google python and came across a statement that is s * 3

faster than s + s + s

where s

has type string

.

Any reason for this?

I googled and found which is faster s + = 'a' or s = s + 'a' in python . But it did not help

+3


source to share


2 answers


Because s * 3

- one operation, while s + s + s

- two operations; it does (s + s) + s

, by creating an extra string object which is then discarded.

You can see the difference by using dis

to look at the bytecode that each generates:

s + s + s

:



  3           0 LOAD_FAST                0 (s)
              3 LOAD_FAST                0 (s)
              6 BINARY_ADD          
              7 LOAD_FAST                0 (s)
             10 BINARY_ADD          
             11 RETURN_VALUE    

      

s * 3

:

  3           0 LOAD_FAST                0 (s)
              3 LOAD_CONST               1 (3)
              6 BINARY_MULTIPLY     
              7 RETURN_VALUE    

      

+18


source


You can also check it out here:

import timeit

print(timeit.timeit("string=''; string='s'+'s'+'s'", number=10000))
print(timeit.timeit("string2=''; string2='s'*3", number=10000))

      



I guess I s*3

see it as one operation versus two s s+s+s

.

+3


source







All Articles