4

If I want to use a bit of unsafe code inside a very time sensitive app - will be there any delay in 'swiching' to unsafe code or thread context switch? C# .net 4

1
  • 1
    Please describe your unsafe code (C# or extern?) Commented Oct 10, 2011 at 13:37

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.)

1 Comment

Yeah, and I'm not typically the first to suggest that. :o)
3

There usually is a penalty from marshaling the parameters and results.

3 Comments

Wouldn't that really refer to interop code (P/Invoke or COM)? IIRC unsafe code can be written in plain IL or C#
+1 You should explain exactly what you are speaking about (PInvoke), especially because all the other response are about the unsafe keyword :-)
I was indeed assuming P/Invoke, @bobb should clarify.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.