简体   繁体   中英

Adding BSON document to list is extremely slow

for (int k = 1; k < list.Count(); k++)
        {
            List<BsonDocument> batch = new List<BsonDocument>();
            for (int i = 0; i < list[k].Count() - 1; i++)
            {
                var obj = new Dictionary<string, object>();
                obj.Add("Status", false);
                obj.Add("Headers", new BsonArray(list[0].ElementAt(0).ItemArray));
                List<string> formattedArray = new List<string>();
                for (int j = 0; j < list[k].ElementAt(i).ItemArray.Count(); j++)
                {
                    formattedArray.Add(JsonConvert.SerializeObject(list[k].ElementAt(i).ItemArray[j]));   
                }
                obj.Add("Values", new BsonArray(formattedArray.ToArray()));
                MongoDB.Bson.BsonDocument BSONDoc = new BsonDocument(obj);
                batch.Add(BSONDoc);
            }
            Insert(batch);
            batch.Clear();
        }

list.Count() = 121

list[k].Count() = 10000

list[k].ElementAt(i).ItemArray.Count() = 137

Here are couple of suggestions from me.

1) Assign list[k].Count() into a variable outside the loop.

2) new BsonArray(list[0].ElementAt(0).ItemArray). You can get this once and assign it to headers. No need to go for multiple times.

3) Finally, Run the Benchmark (using stopwatch) to see sections that are more time consuming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM