简体   繁体   English

Python list pop()比list [1:]慢得多

[英]Python list pop() much slower than list[1:]

I recently wrote a quick and dirty BFS implementation, to find diamonds in a directed graph. 我最近编写了一个快速而肮脏的BFS实现,以在有向图中找到菱形。 The BFS loop looked like this: BFS循环如下所示:

while toVisit:
    y = toVisit.pop()
    if y in visited: return "Found diamond"
    visited.add(y)
    toVisit.extend(G[y])

( G is the graph - a dictionary from node names to the lists of their neighbors) G是图形-从节点名称到其邻居列表的字典)

Then comes the interesting part: I thought that list.pop() is probably too slow, so I ran a profiler to compare the speed of this implementation with deque.pop - and got a bit of an improvement. 接下来是有趣的部分:我认为list.pop()可能太慢了,所以我运行了一个探查器来比较此实现与deque.pop的速度-并做了一些改进。 Then I compared it with y = toVisit[0]; toVisit = toVisit[1:] 然后,我将其与y = toVisit[0]; toVisit = toVisit[1:] y = toVisit[0]; toVisit = toVisit[1:] , and to my surprise, the last implementation is actually the fastest one. y = toVisit[0]; toVisit = toVisit[1:] ,令我惊讶的是,最后一个实现实际上是最快的。

Does this make any sense? 这有道理吗? Is there any performance reason to ever use list.pop() instead of the apparently much faster two-liner? 是否有任何性能原因要使用list.pop()而不是明显快得多的两层线?

You have measured wrong. 你测错了。 With cPython 2.7 on x64, I get the following results: 在x64上使用cPython 2.7,我得到以下结果:

$ python -m timeit 'l = list(range(10000))' 'while l: l = l[1:]'
10 loops, best of 3: 365 msec per loop
$ python -m timeit 'l = list(range(10000))' 'while l: l.pop()'
1000 loops, best of 3: 1.82 msec per loop
$ python -m timeit 'import collections' \
         'l = collections.deque(list(range(10000)))' 'while l: l.pop()'
1000 loops, best of 3: 1.67 msec per loop

使用生成器来提高性能

python -m timeit 'import itertools' 'l=iter(xrange(10000))' 'while next(l, None): l,a = itertools.tee(l)'

1000000 loops, best of 3: 0.986 usec per loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Numpy数组比列表慢得多 - Numpy array is much slower than list 链表总是比python列表慢吗? - Is linked list always slower than python list? 在Cython中使用C创建的一组列表比纯Python慢​​得多 - 为什么? - Taking a Set of a List created using C in Cython is much slower than pure Python - Why? 为什么遍历列表比遍历python中的迭代器要慢得多? - Why would iterating over a list be much slower than iterating over an iterator in python? 列表理解真的比str.replace慢得多吗? - Is list comprehension really much slower than str.replace? 为什么+运算符在创建列表时比append()慢得多? - Why is + operator much slower than append() when creating a list? numpy 数组赋值比 python 列表慢 - numpy array assignment is slower than python list Python:为什么列表理解比for循环慢 - Python: Why is list comprehension slower than for loop Python:添加预生成列表的查找后,isPrime函数要慢得多吗? - Python: isPrime function much slower after adding lookup of pregenerated list? 为什么 tf.concat 比 np.concatenate 和本机 python 列表的“附加”慢得多? 如果可能,我们应该避免吗? - Why is tf.concat much slower than np.concatenate and the “append” of the native python list? Should we avoid if possible?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM