储备内存在Python列表? [英] Reserve memory for list in Python?

查看:147
本文介绍了储备内存在Python列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在Python编程,是可以保留的内存,将与已知数量的项目填充一个列表,这样,当构建它的列表不会被重新分配几次?我已经通过了文档的Python列表类型看,并没有发现任何东西,似乎这样做。然而,这种类型的列表建设的显示在我的code的一些热点,所以我想让它尽可能高效。

When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.

编辑:另外,它甚至是有意义的做这样的事情是在诸如Python语言?我是一个非常有经验的程序员,但新的Python和仍然得到其做事方式的感觉。是否Python的内部分配的所有在单独的堆空间物体,击败试图最小化分配,或像整数元为宗旨,花车等直接存储在列表?

Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate all objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?

推荐答案

下面是四种形式:


  • 增量列表创建

  • pre分配列表

  • array.array()

  • numpy.zeros()

 

python -mtimeit -s"N=10**6" "a = []; app = a.append;"\
    "for i in xrange(N):  app(i);"
10 loops, best of 3: 390 msec per loop

python -mtimeit -s"N=10**6" "a = [None]*N; app = a.append;"\
    "for i in xrange(N):  a[i] = i"
10 loops, best of 3: 245 msec per loop

python -mtimeit -s"from array import array; N=10**6" "a = array('i', [0]*N)"\
    "for i in xrange(N):" "  a[i] = i"
10 loops, best of 3: 541 msec per loop

python -mtimeit -s"from numpy import zeros; N=10**6" "a = zeros(N,dtype='i')"\
    "for i in xrange(N):" "  a[i] = i"
10 loops, best of 3: 353 msec per loop

这说明 [无] * N 是最快和 array.array 在这种情况下最慢

It shows that [None]*N is the fastest and array.array is the slowest in this case.

这篇关于储备内存在Python列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆