C# vs C++/CLI vs PInvoke Performance – Part III

I have demonstrated that C++/CLI vs P/Invoke Performance difference in Part I by using all different wrappers to pinvoke C++ method of sqrt of a native C++ DLL. Since I already included C# version of sqrt in the comparison, I will include comparison of C# version of any native c++ method I used in the future blogs, I will try to optimize every piece of C#, C++ and C++/CLI code as possible as I can, otherwise, it won’t be accurate at all. The C# wrapper used to pinvoke C++ DLL was generated by our PInvoke Interop SDK – A C# Wrapper Generator for C++ DLL.

I added the following methods to the original C++ Calculator class. I choose a simplified implementation(it could overflow depending on the parameters passed in) of hypot because the implementation itself is not that important to our test.

When I built the C++ native DLL, I tried to optimize it as possible as I can, So I optimized the dll build for maximize speed and favor fast code.

And I also enabled SIMD Extensions 2, I tried and it did show it improved the performance.

C++/CLI wrapper code is still very simple, but I had to write the method signature one more time. This is why I do not prefer C++/CLI, I have to repeat every method signature I define in the C++ class even it does not require marshaling.

The C# Wrapper methods code are presented below.

Now, the complete C# testing code.

and then the testing code for double version Hypot.

Now, let’s look at the result of calling the two versions of Hypot methods.

Float Version of Hypot

Doube version of Hypot

The result is what I expected, C++/CLI is the worst performer in both case. The C# version of hypot is the best since there is not much math operation involved in this test and the time to setup the thunk is significant, and we had to push two float or double parameter to the stack, it did cost more CPU time for .NET framework to setup the calling stack. Our C# wrapper class performed very close to the C# version of hypot when the direct call to the P/Invoke method is used, that is the fastest way to pinvoke C++ class method. If you define the hypot as static method, the performance is so close to the C# version and it actually could be better if the math operation is more complicated, which means we can probably build a C# Math library wrapper on top of any existing fast-performance C++ library and the performance could be better than a C# version of Math library.

Stay tuned, I will present you C# vs C++/CLI vs PInvoke Performance Part IV.

Translate »