python-chess
python-chess copied to clipboard
Make Pieces immutable and return them from cache
This PR makes Piece a frozen dataclass and adds a cache for them. For end users (and the library itself of course) this change is invisible API-wise.
However, there is a visible performance increase (even if the test suite is not necessarily the best indicator):
hyperfine 'git checkout master; git clean -fdx; py.test --count=10 test.py' 'git checkout immutable-pieces; git clean -fdx; py.test --count=10 test.py'
Benchmark 1: git checkout master; git clean -fdx; py.test --count=10 test.py
Time (mean ± σ): 6.405 s ± 0.411 s [User: 5.249 s, System: 0.404 s]
Range (min … max): 6.120 s … 7.537 s 10 runs
Benchmark 2: git checkout immutable-pieces; git clean -fdx; py.test --count=10 test.py
Time (mean ± σ): 6.246 s ± 0.131 s [User: 5.218 s, System: 0.394 s]
Range (min … max): 6.126 s … 6.591 s 10 runs
Summary
'git checkout immutable-pieces; git clean -fdx; py.test --count=10 test.py' ran
1.03 ± 0.07 times faster than 'git checkout master; git clean -fdx; py.test --count=10 test.py'
This will also likely have a nice memory usage effect.
Let me know what you think :)
Hi, thanks! I like this patch.
Even as is, pieces are intended to be immutable (no setters, provides __hash__). But that's not documented, so this is technically still a bc break and needs to wait for a future version 2.x.