I was wondering what is the fastest way in python to create an empty string to attach more strings to it later on. However, I found that interestingly it's way faster to init a string via ""
than str()
. Can someone shine a light on this? I guess str() is just coming with a lot of overhead like typecheck etc.
Here is what I tried:
%timeit ""+"a"
7.63 ns ± 0.0376 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%timeit str()+"a"
58.2 ns ± 0.253 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Because calling a function requires looking up that function and calling it. "" + "a"
can just be interpreted as "a"
. Using dis
:
>>> import dis
>>> dis.dis("str() + 'a'")
1 0 LOAD_NAME 0 (str)
2 CALL_FUNCTION 0
4 LOAD_CONST 0 ('a')
6 BINARY_ADD
8 RETURN_VALUE
>>> dis.dis("'' + 'a'")
1 0 LOAD_CONST 0 ('a')
2 RETURN_VALUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With