Performance Considerations with P/Invoke

As you probably already guessed, all of the nice things that the runtime does for you as you call unmanaged code don't come for free. However, the picture is not bleak enough for you to consider dumping interop with unmanaged code for a full port or other options.

It is estimated that each P/Invoke call requires between 10 and 30 x86 assembly instructions. This means that the overhead is small. Perhaps you have a 1Ghz Pentium and each of those 30 instructions takes one clock cycle to complete. That would mean that the overhead for a P/Invoke call is approximately 0.03 microseconds. Even if each instruction took two clock cycles to complete, that would still only be 0.06 microseconds. Clearly, the overhead ...

Get .NET Common Language Runtime Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.