Preallocating some memory in a large memory heap

I am working on a C # application and this application faces a memory crunch because many objects get memory allocation in a bunch of large objects.

My C # application needs to work with many large files (like a string object), and therefore the memory for this string type object gets allocated again and again from the heap of the large object (which leads to LOH fragmentation).

Since a string is an immutable object, new memory in LOH is always assigned to this object. My question is: is there a way, I can preallocate some memory in a large heap of an object and always allocate the same memory for a string object.

Here's what in more detail: As I said, I process these large files. To do the processing, I have to convert it to a string. Even if I use stringBuilder, it will not be very useful, because as soon as I convert it to String, the separate memory for this is allocated in LOH.

So, I expected to allocate a bunch of let say 100 KB in memory, and whenever I read a new file and convert it to a string, these 100 KB are allocated.

+3
source share
3 answers

You should use an object StringBuilderto work with strings, since it is a mutable string and provides many methods for working with it.

, . - , Intern -

+3

, , - (). () , , .

StringBuilder :

var buffer = new StringBuilder(LargestExpectedSize);

LOH. () StringBuilders List<> s

+1
source

All Articles