在运行时弹出,删除和删除之间的区别 - python

我进行了一些测试,以查看pop,del和remove之间的运行时是否有所不同。我预计remove和pop / del之间会有区别,因为remove搜索值并将其删除,而pop / del删除索引。

考试:

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

结果是:

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

正如您所看到的,删除操作要差得多(如预期的那样),但是弹出操作的速度比删除操作要慢约50%-60%(取决于运行)。

这是为什么? (我尝试搜索它(我猜是它的实现),但是找不到原因。也许是我写它的原因?)

python大神给出的解决方案

通过本文中的评论之一转到接受的answer,它表示pop被转换为函数调用,而del充当原语,这就是为什么pop比del慢的原因