Is the equivalent memory used by an array of ints against an array of structures having only one int?

Given the following structure ...

struct Cell { int Value; } 

and the following matrix definitions

 var MatrixOfInts = new int[1000,1000]; var MatrixOfCells = new Cell[1000,1000]; 

which matrix will use less memory space? or are they equivalent (byte per byte)?

+6
source share
3 answers

Both are the same size because the structures are processed like any other type of value and allocated to the heap.

 long startMemorySize2 = GC.GetTotalMemory(true); var MatrixOfCells = new Cell[1000, 1000]; long matrixOfCellSize = GC.GetTotalMemory(true); long startMemorySize = GC.GetTotalMemory(true); var MatrixOfInts = new int[1000, 1000]; long matrixOfIntSize = GC.GetTotalMemory(true); Console.WriteLine("Int Matrix Size:{0}. Cell Matrix Size:{1}", matrixOfIntSize - startMemorySize, matrixOfCellSize - startMemorySize2); 

Here's a bit of fun from Jeffrey Richter about how arrays are allocated http://msdn.microsoft.com/en-us/magazine/cc301755.aspx

+1
source

Using the sizeof operator in C # and executing the following code (in Mono 3.10.0), I get the following results:

  struct Cell { int Value; } public static void Main(string[] args) { unsafe { // result is: 4 var intSize = sizeof(int); // result is: 4 var structSize = sizeof(Cell); } } 

So it looks like the integer and structure storing the integer consume the same amount of memory, so I assume that the arrays will also need the same amount of memory.

+1
source

In an array with value type elements, all elements must be of the same type. An object containing an array must store information about the type of elements contained in it, but this information is stored only once for each array, and not once for each element.

Note that since arrays receive special processing in the .NET Framework (compared to other types of collections), arrays of a structural type will allow the elements of structures contained in them to act "in place." As a result, if you can limit yourself to storing the structure inside the array (and not some other type of collection) and can minimize unnecessary copying of instances of the structure, you can effectively work with structures of almost any size. If you need to store a collection of things, each of which will be associated with four values โ€‹โ€‹of Int64 and four values โ€‹โ€‹of Int32 (a total of 48 bytes), using an array of eight open-field structure elements can be more efficient and semantically cleaner than representing each thing with using four elements from Int64[] and four elements from Int32[] , or using an array of references to unexpanded modified class objects.

+1
source

Source: https://habr.com/ru/post/977744/


All Articles