3

I have this method that is expected to return a string but the string is pretty big maybe in GB. Currently this runs into out of memory exception.

I was thinking I would write to a file (random filename) then read it delete the file and send back the response. Tried MemoryStream and StreamWriter that too ran into out of memory exception.

Did not want to initialize StringBuilder with a capacity since the size was not known and I think it needs a continuous block of memory.

What is the best course of action to solve this problem?

    public string Result()
    {
        StringBuilder response = new StringBuilder();
        for (int i = 1; i <= Int.Max; i++)
        {
            response.Append("keep adding some text {0}", i);
            response.Append(Environment.NewLine);
        }

        return response.ToString();
    }
4
  • Can you show real code? Commented Mar 8, 2016 at 0:26
  • If you used StreamWriter, and it's backing strategy was to write to memory then, yes, you would get a OutOfMemory exception. You might try using a file stream, such as one that writes to the operating system's transient store (e.g., the temp directory). If performance is not a concern, you can simply call Flush() on the file stream after you write to it. Though, one wouldn't be wrong suggesting that you just write straight to a file in that case, with no buffering. Commented Mar 8, 2016 at 0:36
  • It is better to store the records piece by piece than dumping them together. Do you have code where you use the Result()? Commented Mar 8, 2016 at 1:54
  • 1
    How are you sending back the response? If this is a web service, you could always write straight to the response stream... Commented Mar 8, 2016 at 8:47

1 Answer 1

4

Even if you could solve the memory problem on the StringBuilder, the resulting string by calling response.ToString() would be larger than the maximum length of a string in .NET, see: https://stackoverflow.com/a/140749/3997704

So you will have to make your function store its result elsewhere, like in a file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.