I use the couchbase lite .net sdk. Calling the ToDictionary() method multiple times causes the memory on my computer to surge rapidly.
using var results = query.Execute().AllResults();
foreach (var result in results) {
// get the returned array of k-v pairs into a dictionary
var order = result.ToDictionary();
orders.Add(order);
}
My database is over 4MB in size, containing approximately 1,000 documents. Each time it runs, the unmanaged memory usage increases by more than 300MB.
You are accumulating each order in orders. It’s going to grow. If you want to see if the memory is a leak or simply the space taken by each order, just remove the adding of order to orders.
But why doesn’t the memory decrease automatically after use?
With each execution, the unmanaged memory increases significantly.
Why would it automatically decrease? There is nothing in the code that you show that releases memory. It just keeps adding to orders.
This code is inside a function that has no return value, and the variable ‘orders’ is not referenced outside the function. If this function is called repeatedly, my computer’s memory will be exhausted. According to C#'s memory recycling mechanism, after the function finishes executing, the managed memory should be automatically released. However, the unmanaged memory on my computer keeps increasing continuously.
If orders is initialized outside the function, the memory won’t be released. Also, C# garbage collection will not occur immediately upon it being released. You can use a memory profiler to sort out memory issues
If you give the versions of the server and sdk you are using, it might help troubleshooting the issue.
I found this comment on an old cblite ticket.
Not disposing an object will not cause a memory leak. Every IDisposable object in the library is implemented with the “dispose with native resources” pattern (i.e. there is a finalizer that will clean up everything if dispose is not called). Dispose just adds performance because the object can skip GC finalization.