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
source to share
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
source to share