> I tried running a test to see how much better using a struct is. I made
> a loop that calls the DLL function 2.5 million times. First I ran using
[quoted text clipped - 3 lines]
> Huh? Is the class approach actually MORE efficient? Any advice would be
> appreciated. Thanks!
Christian,
>While a struct sounds more low-level, it resides in managed
>memory just like a class and will be pinned (and possibly copied
>and layouted?) before passing a pointer as well.
If it's stack allocated there's no need for pinning.
>Mind that there may be hidden penalties for keeping objects
>pinned when memory is allocated or garbage is collected.
Exactly, that's why I could see a small advantage to using a struct in
this case. But I doubt the difference is of any significance in a real
application.
>Finally, your struct could actually be represented as an
>array with four elements. Passing a blittable array may be
>a lot faster than passing a struct. You could even wrap it
>in a class to provide friendly property accessors.
Why woud it be faster to pass a blittable array than a blittable
struct?
Mattias

Signature
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Christian Fröschlin - 31 Aug 2006 09:28 GMT
Mattias,
> If it's stack allocated there's no need for pinning.
> Why woud it be faster to pass a blittable array than a blittable
> struct?
Both of these are of course very good points ;)
My reply was a bit biased regarding my last evaluation of
struct vs. array performance in a more specific context,
where the data needed to persist as a class member and
was therefore never stack-based, also, my functions
expected arrays of structs rather than structs.
I don't think I have the code anymore, but there was a
significant difference between passing an array of structs
containing a single blittable member and a simple array of
that blittable type, although I would have expected both
of these to represent the same blittable data. You can
look for an older thread in this newsgroup titled
"P/Invoke efficiency for structs and arrays".
At the time I concluded there were some nifty optimizations
going on when passing arrays of basic types from managed heap,
as this seemed to be much faster even compared to manually
pinning the array and passing an IntPtr.
MLM450@hotmail.com - 31 Aug 2006 12:24 GMT
Although the comparison of using an array versus not using one has its
place, it does not impact my situation. The example code in my initial
post was just that, an example. The structure I showed was one of many
I am dealing with. The others are not as simple.
> Mattias,
>
[quoted text clipped - 23 lines]
> as this seemed to be much faster even compared to manually
> pinning the array and passing an IntPtr.
MLM450@hotmail.com - 31 Aug 2006 12:32 GMT
Christian and Mattias,
Many thanks to both of you. Your input is very helpful.