Replies: 3 comments 4 replies
-
Is suggest reading https://docs.micropython.org/en/latest/reference/speed_python.html#ram-allocation |
Beta Was this translation helpful? Give feedback.
-
Not really, unlike Rust the Python language doesn't have any concept of a reference to a variable on the stack. Some variable types like (small) integers and floats are allocated on the stack and passed by value[1], but everything else (strings, bytes, lists, dicts, slices[2] etc) is an object passed by reference and is allocated on the heap[3]. Similarly, importing a code module (even a pre-compiled one) may require one or more heap allocations.
There is an API for this - https://docs.micropython.org/en/latest/library/micropython.html#micropython.heap_lock . MicroPython also locks the heap in hard interrupt handlers and some other internal states where Python allocations are forbidden. However, you may find writing code to run with the heap permanently locked is very limiting. You can track total memory allocated via the
You can compile MicroPython with a custom Python heap size, so you can make a smaller heap and trigger a MemoryError earlier if you've used too much. However there's still only one Python heap. Efficient MicroPython code minimises large heap allocations after startup (i.e. reusing any significant buffer objects, etc), however some small short-lived allocations are almost inevitable when using a language like Python. Generally this pattern doesn't become a problem (apart from the potential Garbage Collection pauses if you have tight timing constraints, and you can still temporarily disable GC via the standard gc.disable() I see @Josverl has linked to the docs about optimising memory usage. This is a good place to further understand "the MicroPython way" for memory management. [1] q.v. copy semantics, |
Beta Was this translation helpful? Give feedback.
-
You can create your own fixed-size block pool by allocating a large bytearray at startup and then managing “allocations” and “frees” manually within this array. |
Beta Was this translation helpful? Give feedback.
-
Is it possible to use MP without a global heap?
(I'm coming from embedded Rust ecosystem where such thing is normal and default having whole libraries heap-less working just with pre-allocated fixed-size-block pools where necessary for more dynamic behaviors or at worst having their own dedicated fixed sized "local" heaps where absolutely necessary e.g. for 3rd party BLE stacks etc..)
Since I'm expecting the answer to my question to be resounding NO I have some following questions:
Beta Was this translation helpful? Give feedback.
All reactions