I will be working with approximately 320,000,000 data points for a high-resolution waveform. Each data point will require 2 floats (XY coordinate) for a total of 8 bytes.
In order to have this memory allocated all at once, I was planning on using a struct
such as the following:
public struct Point
{
public float X; //4-bytes
public float Y; //4-bytes.
}
Since a struct is a value type, I am assuming that it consumes only the amount of memory necessary for each variable, as well as some small, fixed amount used by the CLR (Common Language Runtime).
Is there a way I can compute how much memory a struct will use during runtime of my application? That is, granted I know the following:
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
Since a struct is a value type, I am assuming that it consumes only the amount of memory necessary for each variable, as well as some small, fixed amount used by the CLR (Common Language Runtime).
Nope. Value types do not have any inherit overhead. That's the trade-off for not being able to support inheritance.
So you just pay for the size of the fields it contains.
Exceptions:
If you stick a struct in a variable of type Object
, it has the object overhead:
I talk about this in a blog post "Of memory and strings". It's implementation-specific, but for the Microsoft .NET CLR v4, the x86 CLR has a per-object overhead of 8 bytes, and the x64 CLR has a per-object overhead of 16 bytes.
What is the memory overhead of a .NET Object
The same thing happens if you cast it to an interface type.
If you stick a struct in an array, the array itself has some object overhead plus an integer to store the array's length. But this is a fixed cost regardless of array length.
If you stick a struct in a List<struct>
, you have two objects: the list and the array used by the list. So twice the per-object cost, plus a pointer from the list to the array, plus an integer to know how much of the array is currently is use.
If you stick a struct in a List
or List<object>
, you have the above overhead, plus the cost of one pointer per item in the list, plus the per-object overhead per item in the list.
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