Optimisation: Direct sequence unpacking

Merged
JA
2mo ago
+200-9

Improve unpacking performance, were value to unpack is either a list or tuple:

a, b = [x, y]
a, b = (x, y)

Before, Monty turned the value to unpack into an iterator, which it then consumed to load onto the stack. However, for lists and tuples we know their size and can just put the values directly onto stack, without going through an iterator.

This brings us much closer to CPython in the unpacking_sequence and nbody benchmarks.


Summary by cubic

Speeds up unpacking of lists and tuples by pushing their items directly onto the VM stack instead of going through an iterator.

  • Adds a fast path for Value::Ref tuples and lists in both unpack_exact and the unpack loop, cloning items straight onto the stack or result vector and growing the operand stack when the unpack exceeds its capacity.
  • Preserves the existing "too many/not enough values" error behavior, including dicts reporting their total size.
  • Adds tests covering tuple/list unpacking, shared references, size mismatch errors, stack growth, and refcount checks for the new path.

Brings Monty close to CPython in the unpacking_sequence and nbody benchmarks.