Does anybody know the memory difference between these two? Or how one would figure it out easily themselves?
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.
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 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).
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.
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 bytesint[2]
: 20 bytesint[1 to 2]
*: 28 bytesint[2, 1]
: 36 bytes
On a 64-bit CLR:Tuple<int, int>
: 24 bytesint[2]
: 32 bytesint[1 to 2]
*: 40 bytesint[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:
* 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With