3
votes

I am very new to .Net programming, roughly 1 year.

few days back i checked few articles related to mixed mode assembly, out of curiosity, i am having trouble to understand a lot of this.

  1. Why Microsoft introduced Mixed-Mode assembly, if P/Invoke can be easily done with C#/VB.NET?

  2. Does the Mixed-mode assembly execute faster than pure .Net assembly?

Since .Net is CLR (much like a VM), so my best guess is assembly compiled under mixed mode will too be in CLR so that will eventually degrade the performance.

Please help me with my confusions!

1
from common sense standpoint MM assemblies should be less performant since there is always a trade of of flexibility and resources being usedsll
yes for now i too think the same, but MM assembly must be extremely useful i guess in some case.Parimal Raj
I think assemblies generated by swig use this strategy to get one single dll containing both the unmanaged and managed code...this definitely makes dependencies management simpler.digEmAll
Looking at msdn.microsoft.com/en-us/library/x0w2664k.aspx it seems mixed mode assemblies were introduced to allow smooth(er) migration of native C++ projects to .NET.M.A. Hanin
so, Mixed Mode assemblies don't execute faster?Parimal Raj

1 Answers

6
votes

The primary use case for mixed-mode assemblies is having to interop with existing C or C++ code. Very common of course.

It doesn't by design make code faster. There's a cost associated with transitioning from managed code to native code execution. It is heavily optimized, if you do it right then you only pay for the cost of writing a cookie on the stack that the garbage collector recognizes so that it will avoid looking through unmanaged stack frames for object references. Costs but a handful of cpu cycles. But additional cost may be incurred when you need to translate data. A string being the canonical example. Or pin a managed object so it can't be moved by the collector, an array being the canonical example.

But yes, you certainly can use mixed-mode assemblies to solve a perf problem. If you can limit the number of times you make a transition and you can take advantage of the C or C++ compiler's ability to generate highly optimized code then you could be ahead. There's no magic formula that says you will and it certainly isn't that easy to beat the jitter. It has a pretty effective optimizer although it can't quite beat a C compiler's optimizer, given that it operates under time constraints. The quality of the code you write matters the most.

Always use a profiler first to eliminate any bloopers, find the actual hot spots and to ensure it is worth trying.