Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of invoking unmanaged code from managed code

Tags:

performance

c#

I have a win32 dll and two applications which uses the same dll. One is written using c in unmanaged space and the other is the .net application which makes call to the unmanaged code using Pinvokes.

Sometimes the performance of the .net application is better than the c application. Technically speaking invoking unmanaged code from .net incurs performance overhead but not in this case.

I checked the msdn reference and there seems to be some kind of preprocessing that happens before actual call is made. During linkage the dll is loaded.

I want to understand in what scenarios .net application outperforms?

like image 706
sundar Avatar asked Sep 30 '11 10:09

sundar


People also ask

What is difference between managed code and unmanaged code?

Managed code is the one that is executed by the CLR of the . NET framework while unmanaged or unsafe code is executed by the operating system. The managed code provides security to the code while undamaged code creates security threats.

Can CLR run unmanaged code?

UnManaged Code: code not written in . NET language and MSIL does not understand what it is and can not run under CLR; like third-party controls we used in our . NET applications which is not created in .

How is unmanaged code executed?

Unmanaged code is executed with help of wrapper classes. Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper). Wrapper is used to cover difference with the help of CCW and RCW.

What is the difference between unsafe code and unmanaged code?

This is responsible for things like memory management and garbage collection. So unmanaged simply runs outside of the context of the CLR. unsafe is kind of "in between" managed and unmanaged. unsafe still runs under the CLR, but it will let you access memory directly through pointers.


1 Answers

The pinvoke marshaller is one of the heaviest optimized chunks of code in the .NET framework. Very important, there's lots of pinvoke you cannot see when running a managed program on an unmanaged operating system. The amount of overhead is highly variable. It is but a handful of cpu cycles when the DLL is already loaded and the arguments to the pinvoked function are simple integral types. To many hundreds of cycles when, say, string conversions are necessary.

In no circumstance is it ever faster than a native call. Measuring overhead that's only a handful of cycles accurately is difficult. And keep in mind that you might unintentionally measure the perf of your test program instead of the pinvoke call.

like image 91
Hans Passant Avatar answered Oct 12 '22 00:10

Hans Passant