nirgn
nirgn

Reputation: 2074

Difference between pop, del, and remove in runtime

I build a little test to see if there is a difference in runtime between pop, del, and remove. I expected to be a difference between remove and pop/del because remove search the value and remove it, and pop/del remove the index.

The test:

import time
list1 = []
list2 = []
list3 = []

for num in xrange(100000):
    list1.append(num)
    list2.append(num)
    list3.append(num)

print len(list1)
ticks = time.time()
for num in xrange(100000):
    list1.pop()

print "list 1 is over", list1
print time.time() - ticks
print "------------------------------------------"

print len(list2)
ticks = time.time()
for num in xrange(99999, -1, -1):
    del list2[num]

print "list 2 is over", list2
print time.time() - ticks
print "------------------------------------------"

print len(list3)
ticks = time.time()
for num in xrange(0,100000):
    list3.remove(num)

print "list 3 is over", list3
print time.time() - ticks

And the result is:

100000
list 1 is over []
0.0269999504089
------------------------------------------
100000
list 2 is over []
0.0169999599457
------------------------------------------
100000
list 3 is over []
2.55900001526

And as you can see, the remove is far worse (as expected), but the pop is slower then the del in about 50%-60% (depending on the run).

Why is that? (I try to search it (i guess it's implementation), but couldn't find the reason. Maybe the reason is in how i wrote it?)

Upvotes: 3

Views: 2984

Answers (2)

Function calls and attribute name lookups + bound method initialization are slow in Python. In the pop case the repeated lookup for list1.pop does attribute lookup and creates a new bound method object for each loop, whereas del just calls the __delitem__ magic method which will be in a slot.

You can make the second one much faster by moving the method lookup out of the loop:

pop = list1.pop
for num in xrange(100000):
    pop()

Upvotes: 1

avinash pandey
avinash pandey

Reputation: 1381

Going By one of the comments in this post to the accepted answer it says that pop gets translated into a function call while del acts as a primitive that's why pop is slower as compared to del

Upvotes: 5

Related Questions