I have a C++ method signature that looks like this:
static extern void ImageProcessing(
[MarshalAs(UnmanagedType.LPArray)]ushort[] inImage,
[MarshalAs(UnmanagedType.LPArray)]ushort[] outImage,
int inYSize, int inXSize);
I've wrapped the function in timing methods, both internal and external. Internally, the function is running at 0.24s. Externally, the function runs in 2.8s, or about 12 times slower. What's going on? Is marshalling slowing me down that much? If it is, how can I get around that? Should I go to unsafe code and use pointers or something? I'm sort of flummoxed as to where the extra time cost is coming from.
Take a look at this article. While it's focus is on the Compact Framework, the general principles apply to the desktop as well. A relevant quote from the analysis section is as follows:
The managed call doesn't directly call the native method. Instead it calls into a JITted stub method that must perform some overhead routines such as calls to determine GC Preemption status (to determine if a GC is pending and we need to wait). It is also possible that some marshalling code will get JITted into the stub as well. This all takes time.
Edit: Also worth a read is this blog article on perf of JITted code - again, CF specific, but still relevant. There is also an article covering call stack depth and its impact on perf, though this one is probably CF-specific (not tested on the desktop).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With