title: C# DateTime stack memory
body: <p>1) <code>DateTime.Now</code> returns a new <code>DateTime</code> instance.</p>
  
  <p>2) <code>DateTime.Subtract</code> returns a new <code>TimeSpan</code> instance.</p>
  
  <p>3) <code>DateTime</code> is a structure so occupies memory in the stack.</p>
  
  <p>4) When a method exits (returns), its stack memory is reclaimed.</p>
  
  <p>Therefore, does the following code save memory (assuming <code>StartTiming</code> method is in the same class containing Main)?</p>
  
  <p><b>Code 1:</b></p>
  
  <p></p>
  
  <pre><code>static Main(){
  
  bool started = true;
  static TimeSpan totalTime = TimeSpan.Zero;
  static DateTime startTime = DateTime.Now;
  
  while(started){
          // my assumption: every time the method is called, the same memory 
          // in the stack will be reused
          StartTiming();
      }
  }
  
  void StartTiming(){
       totalTime = DateTime.Now.Subtract(startTime);   
  }
  </code></pre>
  
  <p></p>
  
  <p>compared to the following code</p>
  
  <p><b>Code 2:</b></p>
  
  <p><code></p>
  
  <pre><code>static Main(){    
  
  bool started = true;
  TimeSpan totalTime = TimeSpan.Zero;
  DateTime startTime = DateTime.Now;
  
  while(started){
       // my assumption: every time this stmt is executed  DateTime.Now 
       // creates a new DateTime instance and Subtract creates a timespan instance
       totalTime = DateTime.Now.Subtract(startTime);
      }
  </code></pre>
  
  <p>}
  </code></p>