1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.