The list in Python has the advantage of being variable in size and being able to store any element type. Instead, it needs more memory than C's array.
Array.array is the same as C's array. Instead of storing only elements in the same type, it uses much less memory.
I compared the memory usage of the two at the bottom.
And even though you didn't ask, it's better to use NumPy than array.array (this is automatically vectorized)
when calculating with arrayimport array
import resource
startMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
mylist = []
for i in range(1,100000):
mylist.append(i)
listMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
myarray = array.array('i')
for i in range(1,100000):
myarray.append(i)
arrayMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print("To make a list:", listMem-startMem)
print("To make an array: ", arrayMem-listMem)
Run Results:
list: 3768320
To make an array: 286720
(It varies slightly from time to time, but the list is always larger than the array)
© 2024 OneMinuteCode. All rights reserved.