Search code examples
c#monojit

Embedding Mono - Overhead of a native -> managed context switch


Anyone got any details on the overhead of a native -> managed context switch in Mono? Namely the overhead caused by calling .NET methods/creating .NET objects using the C API.


Solution

  • The current API for invoking a managed method from C code has these kinds of overhead:

    • It does some locking and hash lookup operations to see if the method you're calling and a synthetized helper method are compiled
    • If the methods are not already compiled to native code they are compiled
    • The actual method invocation is fast and contrary to the speculation in some of the answers no marshaling overhead happens, so blittable types and other such considerations don't apply
    • If the return type is a valuetype then the value is boxed: this causes some GC overhead. Note that for methods returning void or a reference type there is no overhead

    We're going to introduce a new API that does away with the overhead in the first and the last points above. In the mean time, unless you're doing millions of calls per second, these overheads are pretty small and almost always dwarfed by the actual managed method called doing real work.