circuitpython/tests/micropython/heapalloc_slice.py
Jim Mussared 5e9189d6d1 py/vm: Avoid heap-allocating slices when subscripting built-ins.
This commit adds a fast-path optimisation for when a BUILD_SLICE is
immediately followed by a LOAD/STORE_SUBSCR for a native type, to avoid
needing to allocate the slice on the heap.

In some cases (e.g. `a[1:3] = x`) this can result in no allocations at all.

We can't do this for instance types because the get/set/delattr
implementation may keep a reference to the slice.

Adds more tests to the basic slice tests to ensure that a stack-allocated
slice never makes it to Python, and also a heapalloc test that verifies
(when using bytecode) that assigning to a slice is no-alloc.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
Signed-off-by: Damien George <damien@micropython.org>
2025-07-16 00:12:47 +10:00

18 lines
297 B
Python

# slice operations that don't require allocation
try:
from micropython import heap_lock, heap_unlock
except (ImportError, AttributeError):
heap_lock = heap_unlock = lambda: 0
b = bytearray(range(10))
m = memoryview(b)
heap_lock()
b[3:5] = b"aa"
m[5:7] = b"bb"
heap_unlock()
print(b)