title: OutOfMemory exception from BinaryFormatter.Deserialize coming from its internal StringBuilder call
body: <p>I have a .NET 4 WCF service that is sending the client some big objects (~115Mb) that get deserialized by the client.  The first time the object comes in it deserializes fine.   However, all subsequent calls throw an <code>OutOfMemoryException</code>.  I've checked to make sure that all of my <code>IDisposables</code> are wrapped in <code>using</code> blocks.  I've looked at the other questions similar to this such as <a href="https://stackoverflow.com/q/4150721/1300754">BinaryFormatter outofmemory exception deserialization
  </a> and <a href="https://stackoverflow.com/q/1136061/1300754">Deserialize from MemoryStream throws OutOfMemory exception in C#
  </a>.  I've tried some of the solutions that people have recommended including using <a href="http://www.codeproject.com/Articles/16017/Optimizing-Serialization-in-NET-part-2" rel="nofollow noreferrer">Simon Hewitt's Optimized Serializer</a>.  However, in the end, he still relies on <code>BinaryFormatter</code> for deserializing objects.</p>
  
  <p>I caught the <code>OutOfMemoryException</code> and looked at the stack trace (see below).  The trace appears to originate from an issue with the memory utilization in the <code>StringBuilder</code> class.  I've read other articles about how <code>StringBuilder</code> can cause memory problems due to the (length * 2) algorithm they use when more space is needed.</p>
  
  <pre><code>at System.Text.StringBuilder.ToString()    
  at System.IO.BinaryReader.ReadString()    
  at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectString(BinaryHeaderEnum binaryHeaderEnum)    
  at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()    
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)    
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)    
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
  </code></pre>
  
  <p>Is there a way to get <code>BinaryFormatter</code> to work differently and not use <code>StringBuilder</code> or is there a good alternative to <code>BinaryFormatter</code> that manages memory better?</p>