且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

真正的不安全code性能

更新时间:2022-10-29 17:32:08

有些性能测量

性能优势并不像你想象的那么大。

我做的正常管理数组访问与不安全的指针一些性能测试在C#。


从Visual Studio 2010的外运行构建,.NET 4,使用结果
任何CPU |在下列PC规格发布版本:的基于x64的PC,1四核处理器。 Intel64位家族6型号23步进10 GenuineIntel〜2833兆赫


 线性阵列的访问权限
 00:00:07.1053664的普通
 00:00:07.1197401不安全*(P + I)线性阵列的访问 - 与指针递增
 00:00:07.1174493的普通
 00:00:10.0015947不安全(* P ++)随机数组访问
 00:00:42.5559436的普通
 00:00:40.5632554不安全使用的Parallel.For(),有4个处理器的随机数组访问
 00:00:10.6896303的普通
 00:00:10.1858376不安全


块引用>

注意不安全 *(P ++)成语居然跑慢。我想这打破了被合并的循环变量,并在安全的版本(编译器生成)的指针访问,编译器优化。

来源$ C ​​$ C在 github上

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.

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.