Skip to content

perf: use slots for Piece, Move, _BoardState and streamline _remove_piece_at - #1228

Open
millisdoe-glitch wants to merge 1 commit into
niklasf:masterfrom
millisdoe-glitch:perf/slots-and-piece-removal
Open

millisdoe-glitch wants to merge 1 commit into
niklasf:masterfrom
millisdoe-glitch:perf/slots-and-piece-removal

Conversation

@millisdoe-glitch

@millisdoe-glitch millisdoe-glitch commented Nov 24, 2026 •

Copy link
Copy Markdown

Motivation & Summary

Since python-chess 2.0.0 requires Python >= 3.11, we can leverage dataclass slots (slots=True) and explicit slots on heavily instantiated core objects to significantly reduce memory allocations and improve attribute access throughput.

Key changes:

  1. slots=True on Piece and Move dataclasses:
    • Both Piece and Move are instantiated millions of times during move generation, PGN parsing, and game tree searches. Enabling slots=True eliminates instance dict overhead.
  2. slots on _BoardState:
    • _BoardState is instantiated on every �oard.push() to preserve undo history on the stack. Adding slots eliminates dictionary allocation for each move pushed to the stack.
  3. Streamlined _remove_piece_at():
    • Inlines piece bitmask inspection directly into _remove_piece_at(), avoiding an initial call to piece_type_at() followed by a duplicate 6-branch if/elif check.

Benchmarks & Verification

  • Full test suite (python test.py):

    • 100% pass rate (328 tests passed, 24 skipped).
    • Runtime reduced from 2.98s down to 2.00s (~32.7% faster).
  • Move generation perft(4) from starting FEN:

    • Runtime reduced from 1.165s down to 0.974s (~16.4% faster).

Zero public API or behavioral changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants