Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🧹 Replace Unsafe.As<bool, byte> with (isWhite ? 1 : 0) #1155

Merged
merged 2 commits into from
Nov 12, 2024

Conversation

eduherminio
Copy link
Member

@eduherminio eduherminio commented Nov 12, 2024

Benchmarks were not conclusive back in the day about this alleged perf. improvement

In @tannergooding words, Unsafe.As<bool, byte>(ref isWhite) can be notably less efficient than isWhite ? 1 : 0 plus
it technically opens the door to undefined behavior (since bool isn't strictly 0 or 1).
Regarding the benchmarks:

a lot of this differences are within 1-20 cycles (roughly 5-10ns)
and they are basically impossible to measure with traditional benchmarking tools
but, the JIT is set up to recognize and optimize the idiomatic patterns
so even if the raw difference is small, the potential difference in broader code can be massive
as it can make the difference on whether things like dead code elimination or constant folding occur

Having unsafe code that doesn't bring any benefits doesn't make sense anyway, and this regression test proved that removing the unsafe solution doesn't lose significant elo, so.. merging

Test  | perf/remove-unsafe-cast
Elo   | 0.38 +- 1.87 (95%)
SPRT  | 8.0+0.08s Threads=1 Hash=32MB
LLR   | 2.94 (-2.25, 2.89) [-3.00, 1.00]
Games | 56200: +15557 -15496 =25147
Penta | [1320, 6574, 12272, 6593, 1341]
https://openbench.lynx-chess.com/test/934/

@eduherminio eduherminio marked this pull request as ready for review November 12, 2024 18:02
@eduherminio eduherminio enabled auto-merge (squash) November 12, 2024 18:02
@eduherminio eduherminio merged commit f20fd48 into main Nov 12, 2024
27 checks passed
@eduherminio eduherminio deleted the perf/remove-unsafe-cast branch November 12, 2024 18:09
@vitorhnn
Copy link

I'm sorry if this has been previously benchmarked, but why not isWhite ? 0 : 6?

@eduherminio
Copy link
Member Author

You're obviously 100% right @vitorhnn, the BenchmarkDotNet benchmark actually tests that.
The only plausible explanation is that I opened this PR at 2 AM 😅

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