Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True Unsafe Code Performance

I understand unsafe code is more appropriate to access things like the Windows API and do unsafe type castings than to write more performant code, but I would like to ask you if you have ever noticed any significant performance improvement in real-world applications by using it when compared to safe c# code.

like image 634
Miguel Avatar asked Mar 21 '11 07:03

Miguel


People also ask

Is Unsafe code faster?

The specification implies unsafe code is inherently faster with pointers.

What does unsafe code mean?

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

How do I allow unsafe code unity?

Create a file in your <Project Path>/Assets directory and name it smcs. rsp then put -unsafe inside that file. Save and close that file. Close and reopen Visual Studio and Unity Editor.

What is safe and unsafe code in C#?

Unsafe code in C# is the part of the program that runs outside the control of the Common Language Runtime (CLR) of the . NET frameworks. The CLR is responsible for all of the background tasks that the programmer doesn't have to worry about like memory allocation and release, managing stack etc.


1 Answers

Some Performance Measurements

The performance benefits are not as great as you might think.

I did some performance measurements of normal managed array access versus unsafe pointers in C#.


Results from a build run outside of Visual Studio 2010, .NET 4, using an Any CPU | Release build on the following PC specification: x64-based PC, 1 quad-core processor. Intel64 Family 6 Model 23 Stepping 10 GenuineIntel ~2833 Mhz.

Linear array access  00:00:07.1053664 for Normal  00:00:07.1197401 for Unsafe *(p + i)  Linear array access - with pointer increment  00:00:07.1174493 for Normal  00:00:10.0015947 for Unsafe (*p++)  Random array access  00:00:42.5559436 for Normal  00:00:40.5632554 for Unsafe  Random array access using Parallel.For(), with 4 processors  00:00:10.6896303 for Normal  00:00:10.1858376 for Unsafe 

Note that the unsafe *(p++) idiom actually ran slower. My guess this broke a compiler optimization that was combining the loop variable and the (compiler generated) pointer access in the safe version.

Source code available on github.

like image 188
Thomas Bratt Avatar answered Sep 25 '22 04:09

Thomas Bratt