This is a C# problem. I have a big object in memory at a certain time. I want to serialize it to a file. There are two steps to do it. 1st, I need to change the object to csv string. 2nd, I need to serialize the csv string.
I have a utility tool, which can append strings to a MemoryStream. I use this utility tool to convert the big object to csv string (in a big trunk of MemoryStream). After converting the big object to a MemoryStream, I create a StreamReader of the MemoryStream and call its method StreamReader.ReadToEnd() to convert the MemoryStream to a (long) string. Then I call info.AddValue("BigObject", string); to serialize the string.
As one can see, in the memory, I will actually hold three copies of the big object. The first one is the object itself, the second will be the MemoryStream, holding the csv string and the third is the string, which is actually a redundant of the MemoryStream.
Is there any way to reduce the memory consumption in this procedure? It seems that if not MemoryStream, I will anyway need to use a StringBuilder to hold the csv string of the big object and I will anyway need to call StringBuilder.ToString() to get the final string. Then the final string and the StringBuilder will coexist in the memory and consume the same amount of memory as currently the MemoryStream and string.
Any idea is welcomed. Thank you.