Thursday 20 September 2018

python - Why is list() 3 times slower than []

I just checked the difference of speed between list() and [], and was surprised to see that list() was 3 times slower than [] for list creation. I tested this in ipython with %timeit magic.



In [1]: %timeit a=list()

10000000 loops, best of 3: 67.5 ns per loop
In [2]: %timeit b=[]
10000000 loops, best of 3: 21.9 ns per loop


Then I thought maybe something is not happening until we actually put an element into it, so I tested the following.



In [3]: %timeit list().append(1)
10000000 loops, best of 3: 143 ns per loop


In [4]: %timeit [].append(1)
10000000 loops, best of 3: 88.7 ns per loop


Now the relationship changed, so then I tested only the appends.



In[5]: a=list()
In[6]: b=[]
In [7]: %timeit a.append(1)
10000000 loops, best of 3: 49.8 ns per loop

In [8]: %timeit b.append(1)
10000000 loops, best of 3: 54.2 ns per loop


What kind of sorcery is this? Why aren't the lists and the appends equivalent?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...