Reputation: 780
Suppose i create a large bytearray. Lets say 1000000 bytes or 1mb total. Does the interpreter reserve 1mb in memory or use memory as the byte array fills. Meaning does a mostly empty bytearray of 1000000 bytes used 1mb in memory?
Upvotes: 1
Views: 4192
Reputation: 880877
sys.getsizeof returns the size of an object in bytes:
In [242]: sys.getsizeof(bytearray(10**6))
Out[242]: 1000025
So indeed bytearray(10**6)
uses about 1MB of space.
Note that while sys.getsizeof
gives an accurate answer for bytearrays, if applied to a container such as a list, it only gives the size of the container, not including the container's contents.
If you need to compute the size of an object including its contents, there is a recipe (referenced in the docs) for that.
Upvotes: 2
Reputation: 1014
I think it is allocated/reserved on construction. The line bellow will increase the memory usage of the interpreter by ~100MB on my system.
b = bytearray(1024*1024*100)
If the documentation does not mention it, I guess its up to the implementation.
Upvotes: 3