Pinned arrays or native arrays?

Announcements and discussion for PInvoke

Pinned arrays or native arrays?

Postby yoavhacohen » Sat Dec 20, 2008 11:02 pm


I'm writing a C# wrapper for a native imaging library.

I can allocate the image data on the managed heap, pin it and pass it to the native structure as a pointer, or allocate it on the native heap.

What's better in terms of time performance?

Thanks in advance,
Posts: 2
Joined: Sat Dec 20, 2008 10:57 pm
Location: Israel

Postby Robert » Mon Dec 22, 2008 9:53 am


I guess this is probably one of those "it depends" answers :-).

Apparently the pinning operation for managed objects is cheap, and I'm guessing that the allocation costs will probably be similar both ways. The major difference is probably going to be in terms of freeing / GC costs.

If you're allocating large objects (>85K I think), they go on to the Large Object Heap (lots more info here), which firstly only gets collected during a Gen 2 GC (the most expensive), and secondly doesn't get compacted, so you might run into virtual memory fragmentation issues, on 32-bit systems at least.

If you allocate natively, you've of course got more control over when you free the memory, and if you're using a lot of these structures, you might get some benefit by not giving the GC so much work to do.

But I suspect the best thing to do is going to be to write it either way, see where your speed issues actually are, and then move on from there - there's no point optimising the memory allocation code if it's only 0.1% of the execution time! ;-).

Hope that helps,
Robert Chipperfield
Red Gate
Posts: 412
Joined: Mon Oct 30, 2006 11:15 am
Location: Cambridge, UK

Return to PInvoke.Net

Who is online

Users browsing this forum: No registered users and 1 guest