- Home /
Array Allocations, references or whole objects
Hi
Let's say I have an array int[100], this would have to allocate
4 (4 bytes in an int) * 100 (length) = 400 bytes
(plus a few bytes for type and length info).
Am I right?
However if I declare an array like: Vector3[100], this would allocate:
4*3 (4 bytes in a float, 3 floats in a Vector3) * 100 = 1200 bytes
Correct?
But now to the real question, if I create an array of class objects. I have my custom class
public class MyClass {
int x = 123;
int y = 456;
}
And if I create an array with one 100 of those class objects, MyClass[100], would this allocate:
4*2 (two ints) * 100 = 800 bytes
(plus a few bytes for type and length info)
or would it only allocate:
4 * 100 = 400 bytes
For the references to the MyClass objects, and the allocation for the MyClass objects would actually be done when calling new MyClass (...);
Thanks in advance, Aron
Answer by johan-skold · Jan 23, 2011 at 10:22 AM
Classes are reference objects in C#, so it would only allocate the 400 bytes required to hold references. If your object had been a struct, it would have been a value type and would have allocated the full 800 bytes.
Also remember that the instances of $$anonymous$$yClass can become scattered across the heap resulting in cache misses iterating through the lot. This is because there is no guarantee your instances line up perfectly. Using a struct would, however. For this reason, many lightweight types are structs.
Ok, so the follow-up question, can I allocate classes so they don't get scattered around? I can't use structs since I need to use references within the object.
And also, "lightweight", how many bytes is that? I have a class using 30 bytes or so, but I have something like 10000+ of them in one array.
If you iterate over them regularly, a struct is surely the way to go. Note that you can pass a struct by reference to methods even if it's a value type. I am unsure if this causes boxing internally but I doubt it. To pass a struct by reference, you specify the parameter with the ref keyword in both the declaration and invocation. Such as "void $$anonymous$$y$$anonymous$$ethod(ref $$anonymous$$yValueType object)" and "this.$$anonymous$$y$$anonymous$$ethod(ref myObject);"
Is there a way to store a reference to a struct, they are usually passed by value, but that wouldn't work in all cases for me. C++ got pointers, but I haven't found something like that in C#.