Closed tmijieux closed 2 years ago
Hi, I've merged your changes in https://github.com/JamesNK/Newtonsoft.Json.Bson/pull/37. The only update I made was to remove the commented-out lines.
Hi, I've merged your changes in #37. The only update I made was to remove the commented-out lines.
Oh nice 👍 , i almost forgot about this. My solution prevent the static memory leak but obviously at the cost of having a higher memory peak during parsing, so another solution i thought of a while later would be to have the four instances in the BsonDataWriter instance directly instead of globally static.
The code where i initially spotted the problem calling your library was this snippet from akavache library: https://github.com/reactiveui/Akavache/blob/95381c27dcb10706ba4ac881253c9db7f26a4ee6/src/Akavache.Sqlite3/SqlLiteCache/SqlRawPersistentBlobCache.cs#L759-L766
private byte[] SerializeObject<T>(T value)
{
var serializer = GetSerializer();
using var ms = new MemoryStream();
using var writer = new BsonDataWriter(ms);
serializer.Serialize(writer, new ObjectWrapper<T>(value));
return ms.ToArray();
}
in this kind of scenario where the writer is use once, and get out of scope immediately after using it there would be no leak (and no concurrency issue)
I understand that the static isntances for Null, Undefined, True and False were probably created to save memory during parsing, but because of the Parent property after the bson is finished writing/reading the whole bson tree hierarchy stay in memory forever or until the next call of the library and the garbage collector collects the previous tree( leaving the last tree in memory)...
I am using this nuget in a xamarin android application and i am often have about 40Megabytes that stays permanently in memory because of this, even when the app in put into background which is rather problematic on low end android devices.
I also see that the algorithm use the Parent property to determine something in
WillClose
method, i did not understand how the library works in detail but i wonder if the algorithm is correct if the parent of all these four values always change and does not reflect the true tree structure ? (if this does not matter (which is probably the case because i never noticed a bug while using this library for a long time?) maybe we could imagine keeping the optimization but instead of putting the values in static variables we could put them in the reader and writer instance )