作为Ignacio points out,这是因为Python分配的内存比所需的多一些.这样做是为了在列表上执行O(1)
.appends
.
sorted
creates a new list超出提供的顺序,sorts it in place并返回它.要创建新列表,请使用Python extends an empty sized list with the one passed;这会导致观察到的过度分配(在调用list_resize
后发生).你可以用list.sort
来证实排序不是罪魁祸首;没有创建新列表的same algorithm is used(或者,众所周知,是performed in-place).当然,那里的尺码是don't differ码.
值得注意的是,这种差异主要出现在以下情况:
因此,通过列表comp:
l = [i for i in range(10)]
getsizeof(l) # 192
getsizeof(sorted(l)) # 200
或列表文字:
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
getsizeof(l) # 144
getsizeof(sorted(l)) # 200
尺寸更小(使用文字时更是如此).
当创建到list
时,内存总是被过度分配;Python knows the sizes和preemptsfuture 的修改,根据大小过度分配位:
l = list(range(10))
getsizeof(l) # 200
getsizeof(sorted(l)) # 200
因此,在列表的大小上没有观察到任何差异.
最后,我必须指出,这是Python的C
个实现,即CPython.这是语言实现的细节,因此,你不应该以任何古怪的方式依赖它.
Jython、IronPython、PyPy和任何其他实现可能/可能不具有相同的行为.