title: How to avoid System.OutOfMemoryException in c# when building a non recombining trinomial tree
body: <p>I have "successfully" implemented a non recombining trinomial tree to price certain fixed-income derivatives. (Something like shown in the picture below - but with three branches that don't reconnect) <img src="https://i.stack.imgur.com/VXgtV.png" alt="this picture"> </p>
  
  <p>Unfortunately it turned out that the number of nodes I can use was severely limited by the available memory. If I build a tree with 20 time-steps this results in 3^19 nodes (so 1,1 Billion nodes)</p>
  
  <p>The nodes of each time step are saved in <code>List&lt;Node&gt;</code> and these arrays are stored in a <code>Dictionary&lt;double,List&lt;Node&gt;&gt;</code></p>
  
  <p>Each node is instantiated via <code>new Node(...)</code>. I also instantiate each of the lists and the dictionary via <code>new Class()</code>  Perhaps this is the source of my error. </p>
  
  <p>Also <code>System.OutOfMemoryException</code> isn't thrown because of the Dictionary/List-Object being to large (as is often the case) but because I seem to have too many Nodes - after a while <code>new Node(...)</code> can't allocate any further memory. Eventually the 2GB max List-Capacity will also kick in I think - seeing as how List grows exponentially larger with each time step.</p>
  
  <p>Perhaps my data-structure is too wasteful or not really suited for the task at hand. </p>
  
  <p>A possible solution could be to save the tree to a text-file thus avoiding the memory-problem completely. This however would necessitate a HUGE workaround.</p>
  
  <p><strong>Edit:</strong>
  To add some more background. I need the tree to price path dependant products. This means that unfortunately I will have to access all the nodes. What is more after the tree has been build I start from the leaves and go backwards in time to determine the price. I also already only generate the nodes I need. </p>
  
  <p><strong>Edit2:</strong>
  I have given the topic some though and also considered the various responses. Could it be that I just need to serialize the respective tree levels to the hard-drive. So basically - I create one time-step (<code>List&lt;Node&gt;</code>) write it to Disk etc. Later on when I start from the leaves - I will just have to load it in reverse oder. </p>