Reserve memory for list in Python?

前端 未结 7 1015
北恋
北恋 2020-12-15 02:33

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

7条回答
  •  暖寄归人
    2020-12-15 03:18

    Here's four variants:

    • an incremental list creation
    • "pre-allocated" list
    • 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
    

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

提交回复
热议问题