title: Why is the first SaveChanges slower than following calls?
body: <p>I'm investigating some performance problems in an experimental scheduling application I'm working on. I found that calls to <code>session.SaveChanges()</code> were pretty slow, so I wrote a simple test.</p>
  
  <p>Can you explain why the first iteration of the loop takes 200ms and subsequent loop 1-2 ms? How I can I leverage this in my application (I don't mind the first call to be this slow if all subsequent calls are quick)?</p>
  
  <pre><code>private void StoreDtos()
  {
      for (int i = 0; i &lt; 3; i++)
      {
          StoreNewSchedule();
      }
  }
  
  private void StoreNewSchedule()
  {
      var sw = Stopwatch.StartNew();
      using (var session = DocumentStore.OpenSession())
      {
          session.Store(NewSchedule());
          session.SaveChanges();
      }
  
      Console.WriteLine("Persisting schedule took {0} ms.", 
        sw.ElapsedMilliseconds);
  }
  </code></pre>
  
  <p>Output is:</p>
  
  <pre class="lang-none prettyprint-override"><code>Persisting schedule took 189 ms. // first time
  Persisting schedule took 2 ms.   // second time
  Persisting schedule took 1 ms.   // ... etc
  </code></pre>
  
  <p>Above is for an in-memory database. Using a http connection to a Raven DB instance (on the same machine), I get similar results. The first call takes noticeably more time:</p>
  
  <pre class="lang-none prettyprint-override"><code>Persisting schedule took 1116 ms.
  Persisting schedule took 37 ms.
  Persisting schedule took 14 ms.
  </code></pre>
  
  <p>On Github: <a href="https://github.com/serra/stackoverflow/tree/master/ravendb/WhyIsMyFirstSaveSoSlowRaven20" rel="nofollow">RavenDB 2.0 testcode</a> and <a href="https://github.com/serra/stackoverflow/tree/master/ravendb/WhyIsMyFirstSaveSoSlowRaven25" rel="nofollow">RavenDB 2.5 testcode</a>.</p>