Does it make any difference to use unsafe inside or outside a loop?
Solution 1:
unsafe
keyword is a marker that you use to tell the compiler that you know what you are doing. Its main purpose is similar to documenting your code: unsafe
block shows parts of your code that you designate as unmanaged territory; there is no impact on the actual execution of code.
With this in mind, it makes sense to reduce the size of this unsafe territory as much as possible, which means that your second approach is better than the first one.
It is worth mentioning that two other alternatives, i.e. marking the method and marking the class with unsafe
, are also inferior to the approach when the unsafe block is placed around the smallest possible portion of the code.
Solution 2:
unsafe
changes which expressions the compiler will accept and produce output for. It imposes no runtime overhead, in and of itself. For any expression that doesn't require unsafe
, the compiler will emit the same code whether its within an unsafe
context or not.
For the specifics of which expressions can only be used within an unsafe
context, I'd recommend consulting section 18 of the C# Language Specification