microbit-foundation / micropython-microbit-v2

Temporary home for MicroPython for micro:bit v2 as we stablise it before pushing upstream
MIT License
41 stars 22 forks source link

Why is memory usage so large #146

Closed rhubarbdog closed 11 months ago

rhubarbdog commented 1 year ago

i have the following program looking at memory usage, why does an array of ascii characters take up 264 bytes and a 102 byte bytearray take 128 bytes?

import gc
gc.collect()
print(gc.mem_free())

xxx = "12345678901234567890" * 5 + "xx"
print(gc.mem_free())
gc.collect()
print(gc.mem_free())

yyy = bytearray(102)
gc.collect()
print(gc.mem_free())

and get results

63984
63712
63712
63584
martinwork commented 1 year ago

It looks like free memory is used up in chunks. Try creating many strings and average the free memory reduction.

dpgeorge commented 1 year ago

Memory is allocated in chunks of 16 bytes. And the bytearray needs an outer object and an inner array to hold the data, so it takes: 16 + 112 = 128 bytes.

For the string, they way you've written it the program will create both the "123...890" * 5 string (length 100) and the final string of length 102. That's at least 256 bytes.

In summary: this is expected.