Memory Optimization Trifecta: `const()`, Interning, Locals

MicroPython enhances speed through intelligent memory handling: the `const()` declaration replaces identifiers with constant values at compile time to avoid runtime dictionary lookups, string interning stores identical strings only once to save RAM, and local variables are accessed more efficiently from the Python value stack than global variables from dictionaries.

The top 3

  1. const(): Compile-Time Memory & Speed Boost: MicroPython's `const()` replaces variable names with literal integer values at compile time, eliminating runtime dictionary lookups and saving RAM. Prepending with an underscore (e.g., `_CONST`) further prevents global dictionary allocation, saving more memory by not being visible outside the module.
  2. QSTRs: MicroPython's Unique String Interning: MicroPython employs QSTRs (uniQue STRings) for efficient string interning, primarily for identifiers. This compile-time optimization stores only one copy of duplicate strings in ROM and RAM, significantly reducing memory footprint and accelerating string comparisons by comparing memory addresses.
  3. Local Variables: Stack Efficiency for Minimal RAM: MicroPython optimizes local variable storage by efficiently allocating them on the stack for function calls, rather than as separate heap objects, which reduces memory fragmentation and overhead, making function execution more memory-lean, especially in recursive or frequently called functions.

Sources

Open the full topic