Unsafe trick to swap movsxd with mov in Unsafe.Add #1285
Unanswered
Sergio0694
asked this question in
Q&A
Replies: 2 comments 3 replies
-
That's the answer. Solves the problem without all that |
Beta Was this translation helpful? Give feedback.
2 replies
-
I would definitely prefer to wait. Our attention and time is a very limited resource these days, better to focus it on topics where the biggest user value is, and try to not get distracted by every shiny little gem :) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey, I've discovered this (arguably ugly) trick while working on the
HighPerformance
toolkit (specifically, here) to basically get rid of themovsxd
(sign extension fromint
to native int) that occurs when usingUnsafe.Add<T>(ref T, int)
. The thing is that this method would only ever be called with positive (and valid) values, so there's no point in paying the performance penalty here for the sign extension. We can just use amov
, which on 64 bit system automatically just sets the upper 32 bit of the target register to 0.Basically, consider this (full
sharplab.io
sample here):This produces the following (when inlined):
That's completely unnecessary. Turns out we can avoid that by doing:
Which gives us:
Now, this is a drop-in replacement, so the idea would be to simply replace all these occurrences in the codebase.
A few considerations to be made though:
I made a quick search and we do have quite a few of these calls (also in loops):
The idea
I think we should consider doing a refactoring with these micro-optimizations in mind.
Specifically, we could:
(nuint)
should work on C# 9 too?)IntPtr
indexer, to remove the sign extension entirely. We can either do this already, just with some slightly uglier code (IntPtr
+ unsafe casts, etc.), or wait for C# 9 to getnint
variables directly.Just food for thought, thought I'd share! 😊
Beta Was this translation helpful? Give feedback.
All reactions