Home > 未分类 > Performance Considerations with P/Invoke

Performance Considerations with P/Invoke

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.

Categories: 未分类
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: