Why is 16 byte the recommended size for struct in C#?

please delete me picture please delete me · Mar 9, 2010 · Viewed 9.1k times · Source

I read the Cwalina book (recommendations on development and design of .NET applications).

He says that a good designed struct has to be less than 16 bytes in size (for performance purposes).

Why exactly is this?

And (more important) can I have larger struct with same efficiency if I run my .NET 3.5 (soon to be .NET 4.0) 64-bit application on Core i7 under Windows 7 x64 (is this limitation CPU / OS based)?

Just to stress again - I need as efficient struct as it is possible. I try to keep it on the stack all the time. The application is heavily multi-threaded and runs on sub-millisecond intervals, and the current size of the struct is 64 bytes.

Answer

RichardOD picture RichardOD · Mar 9, 2010

You're misquoting the book (at least the 2nd edition). Jeffrey Richter states value types can be more than 16 bytes if:

You don't intend to pass them to other methods or copy them to and from a collection class.

Additionally Eric Gunnerson adds (regarding the 16 byte limit)

Use this guideline as a trigger to do more investigation.

It is simply not true that a struct "has to be less than 16 bytes in size". It all depends on usage.

If you are creating the struct and also consuming it and are worried about performance then use a profiler comparing a struct vs class to see which works best for you.