Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: What is the maximum recommended size of a value type?

Tags:

.net

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.

like image 676
Jonathan Allen Avatar asked Oct 05 '10 01:10

Jonathan Allen


2 Answers

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

Ref: Choosing Between Classes and Structures

like image 59
Amry Avatar answered Oct 16 '22 22:10

Amry


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.
like image 36
Michael Petrotta Avatar answered Oct 16 '22 21:10

Michael Petrotta