tags:

views:

71

answers:

2

What is the maximum recommended size of a value type? I think I read that Microsoft suggests that they are not being larger than 16 bytes, but I can't find the reference.

+2  A: 

I found a discussion and a loose recommendation on MSDN, "Using Classes and Structures in Visual Basic .NET":

If your application makes a large number of copies of a variable, the memory required for that variable can be a factor that determines whether it should be a value type or a reference type. There is a trade-off between copying all the bytes of a value type as opposed to allocating a new reference type on the heap. The more copies of a variable your application makes, the more important this distinction becomes.

A theoretical observation might serve as an initial guideline. Suppose you write a test application that does the following:

[..]

Depending on the execution platform and the loading from other tasks, you are likely to observe the following:

  • If the common data size is less than 16 bytes, the structure instance copy loop might be slightly faster than the class instance copy loop.
  • If the data size is 16 bytes, the loops might be approximately equal in timing.
  • If the data size is greater than 16 bytes, the class loop is likely to be faster.

And later, something more definitive at Choosing Between Classes and Structures:

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
Michael Petrotta
Argh, I'm too slow, found the same two articles :) What strikes me as odd though is that "Value Type Usage Guidelines" says "types that meet **any** of the following criteria". Surely "any" isn't good, what if I have an immutable 4x4 Matrix of doubles? That would be rather large for a value type. I think, with the exception of "act like primitive types", "meet **all** requirements" would be more appropriate.
pgroke
@pgroke: Amry's link is better. Mine was from 1.1 days, and his has been edited/fixed since then (I'm thinking they really wanted to say *all* instead of *any*) I've changed my link - Amry, hope you don't mind.
Michael Petrotta
@Michael: Nope, I don't mind at all ;)
Amry
+3  A: 

Yes, Microsoft did suggest for struct not to be larger than 16 bytes.

Ref: Choosing Between Classes and Structures

Amry