Skip to the content.

gc — garbage collection

import gc

MicroPython has a real garbage collector (mark-and-sweep across the 1 MB Python heap on this port). Mostly you don’t need to think about it; gc lets you tune / observe.

Functions

gc.collect()

Force a collection. Returns None.

gc.collect()

gc.enable() / gc.disable()

Turn the GC on or off. By default it’s on, with collection triggered when an allocation can’t be satisfied.

gc.disable()
# performance-critical section with predictable allocation
gc.enable()

gc.mem_alloc() / gc.mem_free()

Bytes currently in use / available on the Python heap.

>>> gc.mem_free()
734528
>>> data = bytearray(100000)
>>> gc.mem_free()
634416
>>> del data; gc.collect()
>>> gc.mem_free()
734528

gc.threshold(n) / gc.threshold()

Set / get the byte allocation threshold that triggers a collection. Default is “as needed”.

Tuning tips


Credit: MicroPython gc docs (MIT).