-
Type: Improvement
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: 2.7.3
-
Component/s: Serialization
BsonClassMapSerializer.SerializeClass (https://github.com/mongodb/mongo-csharp-driver/blob/dc2dbb5ff06fdea80b44a8c2295e542f166ccb16/src/MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs#L579)
calls .ToList() unconditionally like this:
var remainingMemberMaps = _classMap.AllMemberMaps.ToList();
This call can easily be avoided by moving the if check at https://github.com/mongodb/mongo-csharp-driver/blob/dc2dbb5ff06fdea80b44a8c2295e542f166ccb16/src/MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs#L584 into the loop at https://github.com/mongodb/mongo-csharp-driver/blob/dc2dbb5ff06fdea80b44a8c2295e542f166ccb16/src/MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs#L602
This helps to reduce allocations which can get substantial as shown by the following profiler output of the serialization of 2m+ complex documents: