Does anybody know the memory difference between these two? Or how one would figure it out ea开发者_Python百科sily themselves?
For a 32-bit CLR, both will have 4 bytes for the lock, 4 bytes for the type handle, and 8 bytes for the two ints. The array, however, will have an extra 4 bytes to store the length (2 in this case), so the array will have 4 bytes overhead.
Sizes (determined by profiling) on 32-bit:
Tuple<int, int>
: 16 bytes
int[2]
: 20 bytes
int[1 to 2]
*: 28 bytes
int[2, 1]
: 36 bytes
On a 64-bit CLR:
Tuple<int, int>
: 24 bytes
int[2]
: 32 bytes
int[1 to 2]
*: 40 bytes
int[2, 1]
: 48 bytes
Note that single-dimensional zero-based arrays of value types are the smallest possible arrays. Using reference types adds another 4 bytes for the type of object being stored (8 bytes on 64-bit). Using non-zero array bases or multiple dimensions makes it use another kind of array type that stores the rank and lower-bound information, adding 8 additional bytes per dimension.
References:
- http://www.codeproject.com/KB/dotnet/arrays.aspx
- http://www.codeproject.com/KB/cs/net_type_internals.aspx?fid=459323&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2567811
- http://msdn.microsoft.com/en-us/magazine/cc301755.aspx
* You can't declare an array with a non-0 lower bound in C#, so I made up the syntax int[1 to 2]
. You can, however call Array.CreateInstance(typeof(int), new[]{2}, new[]{10});
to create an array with 2 elements, at index 10 and 11. Of course since such arrays cannot be represented directly in C#'s type system, they aren't terribly useful, but they provide an interesting data point.
A Tuple<int, int>
uses the same memory as class with two integer fields. An array on the other hand, has a fairly large internal data structure (called ArrayOpScript
in the SSCLI) that is at least 32-bytes plus another data structure (called ArrayOpIndexSpec
) for each rank (in this case one) of size 16 bytes. So an array almost certainly uses several factors more memory than a Tuple
.
精彩评论