Reduce MutableProxy per-element overhead and cache per-field proxies
Closed
AL
2mo ago+88+88+01234567890123456789-7-7-0123456789
Linear: ENG-10094
Description
MutableProxy._wrap_recursivewalked 5 stack frames (_is_called_from_dataclasses_internal) for every element retrieved through a proxy, before the cheapis_mutable_typecheck that usually decides nothing needs wrapping. The checks are reordered so immutable elements (the common case: ints, strings in a proxied list) skip the frame walk entirely. The dataclasses-internal check still runs for mutable values, preservingdataclasses.asdict/astuplebehavior.BaseState._get_attributeconstructed a freshMutableProxyon every read of a mutable state var. The proxy is now cached per instance and field name, invalidated by identity when the underlying value is reassigned. The cache is excluded from pickling (__getstate__), andcopy/deepcopyalready round-trip through__getstate__, so copies never share or carry proxies.
One deliberate nuance: when _wrap_recursive receives an already-proxied value and is called from dataclasses internals, it now returns the unwrapped value (previously the still-wrapped proxy), matching the documented intent of that path.
Benchmarks (GitHub Actions runner, run, 2 passes each)
| Case | main | this PR | speedup |
|---|---|---|---|
| iterate 1000-int list via proxy | 0.977 / 0.973 ms | 0.219 / 0.214 ms | ~4.5x |
| index 1000 elements via proxy | 1.204 / 1.171 ms | 0.396 / 0.381 ms | ~3.0x |
| read mutable var attribute | 2.82 / 2.87 us | 1.17 / 1.15 us | ~2.4x |
cProfile (20 iterations + 2000 attr reads): _is_called_from_dataclasses_internal (20,000 calls, 0.028s cumulative) disappears from the profile; total function calls drop from 168k to 72k.
Type of change
- Bug fix (non-breaking change which fixes an issue)
Changes To Core Features:
- Have you added an explanation of what your changes do and why you'd like us to include them?
- Have you written new tests for your core changes, as applicable?
tests/units/istate/test_proxy.py: proxy reused across reads and invalidated on reassignment; cache never serialized (pickle round-trip rebinds proxies to the restored state); iteration yields plain immutables while mutable elements stay wrapped.
- Have you successfully ran tests with your changes locally?
š¤ Generated with Claude Code
https://claude.ai/code/session_01G8cXh3TUbNtbjm2ERqE62X
Generated by Claude Code