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 is small. In addition to that is the cost of marshaling each argument. It is hard to estimate what this overhead is, but if it concerns you, do some measurements to see how much overhead that marshaling your data is costing. Remember:

If the arguments that you are passing and the return result are blittable types, then marshaling overhead is zero (or close to it). If you are consistently passing long strings to be translated from Unicode to ANSI, then the marshaling overhead can be significantly more. All in all, the overhead for P/Invoke is small. It takes a contrived set of code to make a case that the overhead for P/Invoke is too high.

Always consider the alternatives. You could port your unmanaged code to managed code so that no overhead is present in calling unmanaged code functions. You could invent other methods that are not portable and might be tied to specific implementations of the CLR. This would be a maintenance nightmare. Clearly, if you need to interop with legacy DLLs, P/Invoke is the best method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.40.207