Ryan Peschel
Ryan Peschel

Reputation: 11756

Allocating a block of memory in C#?

In my program I am allocating a lot of arrays (millions) and they are all quite small in size.

Because it is faster to allocate a large block of memory than small ones repeatedly, I was looking for a way to just allocate a large block of memory, keep a pointer to the current position in that block to draw the next array from, and then allocating another large block when that one is exhausted.

Is this possible to do in C# and if so, how? I have a feeling Marshal.AllocHGlobal may be what I'm looking for, but I'm not quite sure if C# has a more managed way of doing so.

As an example, I'd like to allocate a memory block of 1,000 bytes, and then later create an array of length 4 that uses the first 4 bytes, and then later create an array of length 3 that uses the next 3 bytes.

Upvotes: 2

Views: 1856

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

It is hard to answer without more context. But it sounds like you're looking for something like ArraySegment which is an abstraction to access the portion of array.

With ArraySegment you can just create a single large array and split it with multiple segments logically.

If the millions of arrays you create are short lived, then it is fine to create and forget them. Garbage collector is good at handling short lived references.

Remember time taken to garbage collection is not directly proportional to the number of objects you create, but proportional to the number of objects which survive the garbage collection. So, if your objects are short lived, you're better off creating many arrays.

Creating a huge array is a bad thing to do if it is more than 85,000 bytes, because it will sit in LOH which is not compacted on GC. No compaction -> Large chances of fragmentation.

Upvotes: 4

Related Questions