Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is str()+"" slower than ""+""

Tags:

python

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)
like image 940
PlagTag Avatar asked Sep 09 '20 18:09

PlagTag


Video Answer


1 Answers

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
like image 105
Boris Avatar answered Oct 28 '22 16:10

Boris