Is there any performance hit or thread context switch on using unsafe code?
If I want to use a bit of unsafe code inside a very time sensitive app - will be there any delay in 'swic开发者_JAVA技巧hing' to unsafe code or thread context switch? C# .net 4
In principle: no. The whole point is that you bypass some of the managed runtime checks and restrictions.
That said, it is theoretically possible that the JIT engine can apply fewer optimizations in rare circumstances, due to the fact that fewer assumptions can be made about the code in the unsafe block. Edit Actually the point about pinning heap memory made by Matthew is a prime example that lies in this direction. The JIT-ter and GC engine are more restricted and can make fewer assumptions
Also, unsafe code requires running with certain permissions so it might not be appropriate for all deplyoment targets.
The time taken to get fixed memory locations and converting indexes to pointers may have negative impacts depending on what you are trying to do. Only real way to know is try it as both safe
and unsafe
and see which is faster. (My experience has been safe work is typically faster... I was very surprised.)
There usually is a penalty from marshaling the parameters and results.
精彩评论