Will a Python list ever shrink? (with pop() operations)

时间:2019-02-18 00:27:00

标签: python python-3.x performance

I have been using .pop() and .append() extensively for Leetcode-style programming problems, especially in cases where you have to accumulate palindromes, subsets, permutations, etc.

Would I get a substantial performance gain from migrating to using a fixed size list instead? My concern is that internally the python list reallocates to a smaller internal array when I execute a bunch of pops, and then has to "allocate up" again when I append.

I know that the amortized time complexity of append and pop is O(1), but I want to get better performance if I can.

1 个答案:

答案 0 :(得分:6)

是的

Python(至少是CPython实现)在后台使用魔术使列表尽可能高效。根据{{​​3}}(2011),为提高效率,对append和pop的调用将动态地按块动态分配和释放内存(必要时过度分配)。如果列表缩小到块大小以下,则它将仅释放内存。因此,在大多数情况下,如果您要执行大量的添加和弹出操作,则不会执行内存分配/取消分配。

基本上,使用这些高级语言的想法是,您应该能够使用最适合您的用例的数据结构,并且解释器将确保您不必担心后台的工作。 (例如,避免微优化,而通常只关注算法的效率)如果您担心性能,建议您使用一种对内存有更多控制权的语言,例如C / C ++或Rust

Python保证了您所指出的append和pop的O(1)复杂性,因此听起来很适合您的情况。如果您想像使用队列一样使用它,并使用速度较慢的list.pop(1)list.insert(0, obj)之类的东西,那么可以考虑使用专用的队列数据结构。