Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Option 1 - nice and simple

private void GetFileReady()
{
    private StringBuilder fileContents = new StringBuilder();
    using (var sr = new StreamReader("C:\A big file.txt"))
    {
        fileContents.Append(sr.ReadToEnd());              
    }
}

Option 2 - less simple

private void GetFileReady2()
{
   private StringBuilder fileContents = new StringBuilder();
   const int bufferSize = 1024;
   var buffer = new Char[bufferSize];
   var count = bufferSize;

   using (var sr = new StreamReader("C:\A big file.txt"))
   {                
       while (count > 0)
       {
           count = sr.Read(buffer, 0, bufferSize);
           fileContents.Append(buffer, 0, count);
       }
   }
}

Would option 2 be better for something esoteric like memory allocation?

share

locked by Jamal Apr 15 '14 at 23:18

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

2 Answers 2

up vote 7 down vote accepted

Is the goal to get a string containing the content of the file? or to add the content of a file to an existing StringBuilder?

if it's the former then Option 1 can drop the string builder altogether ... or better yet.

string value = File.ReadAllText("C:\A big file.txt");

if it's the latter then you might want to think about using StringBuilder.EnsureCapacity() to avoid the overhead of resizing the buffer more then it needs to.

share
    
cool, I wasn't aware of EnsureCapacity. I'll use that to size the stringbuilder from FileInfo – Rob Feb 28 '11 at 15:08

I don't think there's a significant difference between your two options when it comes to memory allocations. In both cases, you're reading the entire file into memory, which trumps any minor differences that might exist in the number of objects allocated by the two options. (Though both options are also immediately discarding those contents since they are only stored in local variables, but I'm assuming that this is just a highly simplified example.)

If you're concerned about memory consumption when using a big file, you need to not read in the entire file all at once. Instead, you should load chunks out of the file as needed by your application, and discard them when no longer needed so the memory can be reclaimed.

share

Not the answer you're looking for? Browse other questions tagged or ask your own question.