The question is not correctly posed. "Unsafe" cannot be faster or slower, because
unsafe
is not a statement which cause generation of some code taking any CPU time. It's merely the statement which allows you to do the pointer operations. So, everything depends on what you do with your pointer operations. The actual performance depends on many factors.
Take the use of
Marshal.Copy
. Its implementation can be optimized, for example, not because this is C++, but because it can use some preliminary created
unmanaged code, somehow optimized. Remember that IL is based on JIT (
http://en.wikipedia.org/wiki/Just-in-time_compilation[
^]). When you use
unsafe
, you still use managed objects, which should be pinned (
LockBits
actually does that), and so one. It's hard to say how it translates into overall performance. I would not be much surprised if you manage to build some other code sample where your pointer arithmetic turns out faster than some other approach.
By the way, if you do your experiment with performance, it's important to exclude the time taken by JIT compilation. How? JIT normally works on per-method basis. So, before measuring timing, you need to make sure that every timed method was already called before at least once, with all the other methods it calls. Use
System.Diagnostics.StopWatch
for timing.
—SA