C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
TestArray1: This contains only 3 object references, for 3 arrays. The array variables such as string[] are only references.
ClassTestArray2: This contains an array of classes. Each class in the array has the same 3 value types.
Info: The string reference actually stores no data unless assigned. Integers and DateTimes are stored inline.
StringsInt, uintDateTimeMain: This method has 2 paths, which you can change by turning the "true" Boolean literal to "false." It uses TestArray1 or TestArray2.
Tools used:
CLRProfiler, 32-bit Windows
C# program that measures memory
using System;
class TestArray1
{
public string[] _value1; // Array of string references
public int[] _value2; // Array of integers
public DateTime[] _value3; // Array of structs
}
class TestArray2
{
public TestClass1[] _class1; // Array of classes
}
class TestClass1
{
public string _value1; // String reference
public int _value2; // Integer
public DateTime _value3; // Struct
}
class Program
{
const int _constant = 10000000; // <-- Number of elements required
static void Main()
{
// True will test the arrays, false will check the classes.
if (true)
{
//
// This tests the memory usage with separate arrays.
//
TestArray1 test1 = new TestArray1();
// Allocate each array.
test1._value1 = new string[_constant];
test1._value2 = new int[_constant];
test1._value3 = new DateTime[_constant];
}
else
{
//
// This tests the memory usage of array of classes.
//
TestArray2 test2 = new TestArray2();
test2._class1 = new TestClass1[_constant];
for (int i = 0; i < test2._class1.Length; i++)
{
// Allocate each class.
test2._class1[i] = new TestClass1();
}
}
}
}
Then: Browse to the x86 folder, and double-click on CLRProfiler.exe. The program will start.
Tip: I usually just take screenshots of the charts instead of saving the files, because I have organization problems.
Measurements
Total: 153 MB
DateTime array: 76 MB
Int array: 38 MB
String references: 8 MB
Info: Memory usage is 267 MB total. This is 229 MB for all class object data and 38 MB for all class references in the array.
And: I am not certain why this occurs, but it also proves the massive memory efficiency gain.
Task manager measurement
Program with three arrays: 40612 KB [smaller]
Program with one array: 276936 KB
Therefore: If you change a class to use three arrays instead of a class array, you do not violate the principles of OOP.
But: This is only useful when only one Employee object will be needed by the caller. And it could lead to more problems.
Factory Pattern