Question: I am considering porting a small portion of the code in a C# project of mine to C/ASM for performance benefits. (This section of code uses many bitwise operations and is one of the few places where there may exist a real performance increase by using native code.) I then plan to simply call the native function in the separate DLL via P/Invoke. Now, the only data that will be passed between the managed and native code will be purely primitive types (bool, int, long, 1D arrays, etc.). So my question is: will there be any significant overhead using P/invoke simply with primitive types? I am aware that there is a substatial overhead when using more complex types, since they need to be marshalled (pinned/copied), but perhaps in my situation it will be relatively efficient (compared to calling the code from within the native DLL itself even)? If someone could clarify this matter for me, explaining the degrees of performance advantages/hits and the reasons behind them, it would be much appreciated. An alternative way to accomplish the whole task would also be welcome, though since C# lacks support for inline assembly/CIL, I don't believe there is one.

Answer: 
I seem to recall hearing that there's at least a 30 machine op overhead for each P/Invoke call. But ignore the theory, profile your options and choose the fastest.
You could generate a compiled, optimized version of your .NET assembly by using `ngen` on the end-user's computer (as part of the install process).

In my experience properly formatted C# (e.g., keep allocation outside of loops) will perform very well.