Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple<int, int> versus int[2] memory usage

Tags:

.net

Does anybody know the memory difference between these two? Or how one would figure it out easily themselves?

like image 355
BobTurbo Avatar asked Jan 13 '11 02:01

BobTurbo


People also ask

Why do tuples consume less memory?

Tuples are stored in a single block of memory. Tuples are immutable so, It doesn't require extra space to store new objects. Lists are allocated in two blocks: the fixed one with all the Python object information and a variable sized block for the data. It is the reason creating a tuple is faster than List.

How is memory allocated to a tuple in Python?

Tuple is stored in a single block of memory. Creating a tuple is faster than creating a list. Creating a list is slower because two memory blocks need to be accessed. An element in a tuple cannot be removed or replaced.

How much memory does a variable take in Python?

How can I know the memory size of variable x? int z=1; This means that there are 4 bytes= 32 bits allocated for z, and the bits are arranged as 00.. 001(31 0's and one 1).

How much memory does a Python list take?

When you create a list object, the list object by itself takes 64 bytes of memory, and each item adds 8 bytes of memory to the size of the list because of references to other objects.


1 Answers

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.

like image 132
Gabe Avatar answered Jan 04 '23 09:01

Gabe