A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used .append(x) when needing to insert items and .pop(0) when needing to remove items.
I know that Python has collections.deque and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?
In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a realloc and free up some of that memory?
解决方案
You won't run out of memory using the list implementation, but performance will be poor. From the docs:
Though list objects support similar
operations, they are optimized for
fast fixed-length operations and incur
O(n) memory movement costs for
pop(0) and insert(0, v) operations
which change both the size and
position of the underlying data
representation.
So using a deque will be much faster.