Reputation: 2340
I was going through the google's python intro and came across the statement that s * 3
is faster than doing s + s + s
where s
is of type string
.
Any reason for that to happen?
I googled and found which is faster s+='a' or s=s+'a' in python. But that didn't help
Upvotes: 3
Views: 435
Reputation: 351
You can also test it yourself here:
import timeit
print(timeit.timeit("string=''; string='s'+'s'+'s'", number=10000))
print(timeit.timeit("string2=''; string2='s'*3", number=10000))
My guess is that s*3
treats it as one operation vs. two with s+s+s
.
Upvotes: 3
Reputation: 122157
Because s * 3
is one operation, whereas s + s + s
is two operations; it's really (s + s) + s
, creating an additional string object that then gets discarded.
You can see the difference by using dis
to look at the bytecode 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
Upvotes: 18