MongoDb中MongoServer.Create()和mongoClient.GetServer()之间的性能差异

本文关键字:之间 性能 GetServer MongoServer Create MongoDb mongoClient | 更新日期: 2023-09-27 18:36:57

请考虑以下代码:

     MongoServer mongo = MongoServer.Create();
        mongo.Connect();
        Console.WriteLine("Connected");
        Console.WriteLine();
        MongoDatabase db = mongo.GetDatabase("tutorial");
        Stopwatch stopwatch=new Stopwatch();
        stopwatch.Start();
        using (mongo.RequestStart(db))
        {
            MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("books");
            for (int i = 0; i < 100000; i++)
            {
                var nested = new BsonDocument
                {
                    {"name", "John Doe"},
                };
                collection.Insert(nested);
            }
        }
        stopwatch.Stop();
        Console.WriteLine(stopwatch.ElapsedMilliseconds);
        Console.ReadLine();

在第一行中,我使用MongoServer.Create(),这是过时的。但是当运行上面的代码时,输出时间为3056(大约 3 秒)。

所以我使用MongoDb文档推荐的这段代码。

 MongoClient mongo = new MongoClient();
            var server = mongo.GetServer();
            MongoDatabase db = server.GetDatabase("tutorial");
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            using (server.RequestStart(db))
            {
                MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("books");
                for (int i = 0; i < 100000; i++)
                {
                    var nested = new BsonDocument
                    {
                        {"name", "John Doe"},
                    };
                    collection.Insert(nested);
                }
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            Console.ReadLine();

在代码上运行时,输出时间为14225(在我的电脑上大约 10 到 14 秒)。为什么由于新版本的mongoDb上的重构代码,我得到了这个性能时间。

MongoDb中MongoServer.Create()和mongoClient.GetServer()之间的性能差异

在使用建议的连接模式时,您很可能会看到较新的驱动程序中默认启用的写入关注之间的差异(如在第二个示例中所做的那样)。

更改是在 2012 年 11 月进行的:

http://docs.mongodb.org/manual/release-notes/drivers-write-concern/

在此更改之前,默认情况下不会确认写入,因此您将看到"更快"的写入。

此处提供了有关 C# 更改的更多详细信息。

如果要尝试使用新样式连接,可以在测试中禁用数据库连接的 WriteConcern:

MongoDatabase db = server.GetDatabase("tutorial", WriteConcern.Unacknowledged);

,然后重新运行测试以比较性能。