[Performance] on_key rebuilds Key/InputState enum members on every keypress #344

Closed
opened 2026-07-10 21:57:31 +00:00 by john · 0 comments
Owner

Problem

PyScene's key handler constructs a fresh IntEnum member on every keypress for both the key and the action:

  • PyObject_CallFunction(PyKey::key_enum_class, "i", ...) (src/PySceneObject.cpp:362)
  • PyObject_CallFunction(PyInputState::input_state_enum_class, "i", ...) (src/PySceneObject.cpp:373)

IntEnum members are immutable singletons, so calling the enum class per event re-does the member lookup/allocation ceremony each time.

Proposed fix

Pre-build the enum members once into a lookup table (array/dict indexed by key code and input state) and return the cached PyObject* (INCREF'd) per event.

Priority note

Frequency is per-input, not per-frame, so this is a smaller win than #(animation) / #(scene-update) — filing for completeness in the same hot-path cleanup sweep. Same class of fix as #331.

Benchmark

Measure enum-member acquisition cost in isolation, before/after. Add to tests/benchmarks/.

## Problem `PyScene`'s key handler constructs a fresh IntEnum member on every keypress for both the key and the action: - `PyObject_CallFunction(PyKey::key_enum_class, "i", ...)` (`src/PySceneObject.cpp:362`) - `PyObject_CallFunction(PyInputState::input_state_enum_class, "i", ...)` (`src/PySceneObject.cpp:373`) IntEnum members are immutable singletons, so calling the enum class per event re-does the member lookup/allocation ceremony each time. ## Proposed fix Pre-build the enum members once into a lookup table (array/dict indexed by key code and input state) and return the cached `PyObject*` (INCREF'd) per event. ## Priority note Frequency is per-input, not per-frame, so this is a smaller win than #(animation) / #(scene-update) — filing for completeness in the same hot-path cleanup sweep. Same class of fix as #331. ## Benchmark Measure enum-member acquisition cost in isolation, before/after. Add to `tests/benchmarks/`.
john closed this issue 2026-07-11 03:02:54 +00:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
john/McRogueFace#344
No description provided.