user176168
user176168

Reputation: 1370

C# array of consecutive objects in memory?

So my understanding of C# is that when dealing with an array of objects (rather than simple types) the array will simply be a consecutive array of references to objects, hence the need to call 'new' on each element to actually create the object for it.

Block[] blocks = new Block[10];

foreach(Block block in blocks)
{
    block = new Block();
}

This I would imagine would spread 'Block' instances all over memory.

I want my actual objects to be stored consecutively in memory is there any way to do this in C#?

Upvotes: 3

Views: 921

Answers (2)

zmbq
zmbq

Reputation: 39039

You're probably worried about L1 cache misses, right?

You're out of luck. Allocating several objects one after the other will most likely result in the objects being consecutive in memory. Unfortunately, when the GC does its job, you might end up with the objects being all over the place.

EDIT: A suggestion

If you really must have them all in one region, you can either make them value types and create an array, or resort to unsafe code and fix them in memory.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

If you make your objects value types (i.e. structs), they will be stored next to each other in an array, the same way the instances of primitives (int, double, etc.) are stored. For example, if you declare

DateTime d[] = new DateTime[10];

your DateTime objects will be stored consecutively in a memory block, because DateTime is a value type. Note that you woulnd't need to call a constructor either: all structs in your array will be initialized and ready to be used.

Upvotes: 2

Related Questions