为什么第一个SaveChanges比跟随调用慢?

时间:2014-09-21 18:20:53

标签: ravendb

我正在调查我正在进行的实验性调度应用程序中的一些性能问题。我发现对session.SaveChanges()的调用非常慢,所以我写了一个简单的测试。

你能解释为什么循环的第一次迭代需要200ms而后续的循环需要1-2 ms吗?我如何在我的应用程序中利用它(如果所有后续调用都很快,我不介意第一次调用这么慢)?

private void StoreDtos()
{
    for (int i = 0; i < 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);
}

输出是:

Persisting schedule took 189 ms. // first time
Persisting schedule took 2 ms.   // second time
Persisting schedule took 1 ms.   // ... etc

以上是针对内存数据库的。使用http连接到Raven数据库实例(在同一台机器上),我得到了类似的结果。第一次通话需要更多时间:

Persisting schedule took 1116 ms.
Persisting schedule took 37 ms.
Persisting schedule took 14 ms.

在Github上:RavenDB 2.0 testcodeRavenDB 2.5 testcode

1 个答案:

答案 0 :(得分:1)

第一次调用RavenDB时,有几件事情必须发生。

  • 我们需要为您的实体准备序列化程序,这需要时间。
  • 我们需要创建与服务器的TCP连接。

在接下来的调用中,我们可以重用已经打开的连接和创建的序列化程序。

相关问题