-
Notifications
You must be signed in to change notification settings - Fork 4.8k
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
Convert some instances of Unsafe.SizeOf and Unsafe.As to regular unsafe code #78741
Conversation
…fe code C# 11 allows use of managed types with pointers and sizeof. Replacing Unsafe.* with regular unsafe code makes the binaries a bit smaller and saves time and memory at runtime.
I couldn't figure out the best area label to add to this PR. If you have write-permissions please help me learn by adding exactly one area label. |
Does it make sense to globally supress the warning in runtime code with this? |
src/libraries/System.Private.CoreLib/src/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs
Show resolved
Hide resolved
The repo coding style seems to prefer targeted I do not have a strong opinion on this. |
I have a somewhat related question, this seemed like a good place to ask 😄 Is this type of transformation also valid? // C# 10
static unsafe void M1(object obj)
{
Unsafe.As<Action>(obj)();
}
// C# 11
static unsafe void M2(object obj)
{
(*(Action*)&obj)();
} The second version is 2 bytes shorter in IL, and doesn't require JIT work to inline the call. AFAIK this should be safe given that taking the address will also address-expose the target, so it'll remain alive. If this is indeed the case and this type of change is ok, I'm wondering whether it wouldn't also make sense to leverage this? I remember there's a bunch of similar cases in the runtime, eg. several |
Yes, it should work fine. It is a bit less readable in my opinion.
Task infrastructure is not small. It would save a drop in a bucket there. I think it would more about style preference rather than perf optimizations there. |
I'm wondering why it emits a warning. What could go wrong with it? Or is it just that previous assumptions about pointers are no longer true? |
It is trying to tell you "hey, this is probably not doing what you are looking for". |
src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/Unsafe.cs
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's stick with the pragmas for this PR but reconsider suppressing globally after we get more experience with mistakes folks might make.
C# 11 allows use of managed types with pointers and sizeof. Replacing Unsafe.* with regular unsafe code makes the binaries a bit smaller and saves time and memory at runtime.