[CSHARP-2506] Reduce allocations in BsonClassMapSerializer.SerializeClass Created: 06/Feb/19  Updated: 28/Oct/23  Resolved: 04/Dec/20

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: 2.7.3
Fix Version/s: 2.12.0

Type: Improvement Priority: Major - P3
Reporter: Daniel Hegener Assignee: Unassigned
Resolution: Fixed Votes: 0
Labels: devexp-product, performance
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: PNG File image-2019-02-06-14-11-21-179.png    

 Description   

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:



 Comments   
Comment by Githook User [ 04/Dec/20 ]

Author:

{'name': 'Daniel Hegener', 'email': 'Daniel.Hegener@fisglobal.com'}

Message: CSHARP-2506: Eliminated .ToList() call in SerializeClass() in order to reduce allocations on hot path
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/84ff74d8d62be06ead9e0e1580a549e66beec8dc

Comment by Daniel Hegener [ 20/Feb/19 ]

PR https://github.com/mongodb/mongo-csharp-driver/pull/365

Generated at Wed Feb 07 21:42:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.