Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[windows] improve memory usage of
CollectionView
Context: #16436 Context: https://github.com/symbiogenesis/Maui.DataGrid/tree/net8-memory-leak A customer sample has a `CollectionView` with 150,000 data-bound rows. Debugging what happens at runtime, I found we effectively were doing: _itemTemplateContexts = new List<ItemTemplateContext>(capacity: 150_000); for (int n = 0; n < 150_000; n++) { _itemTemplateContexts.Add(null); } Then the items were created as you scroll each row into view: if (_itemTemplateContexts[index] == null) { _itemTemplateContexts[index] = context = new ItemTemplateContext(_itemTemplate, _itemsSource[index], _container, _itemHeight, _itemWidth, _itemSpacing, _mauiContext); } return _itemTemplateContexts[index]; This code accesses the indexer multiple times, into a `List<T>` with 150,000 `null` items. To improve this: * use a `Dictionary<int, T>` instead, just let it size dynamically. * use `TryGetValue(..., out var context)`, so each call accesses the indexer one less time than before. * use either the bound collection's size or 64 (whichever is smaller) as a rough estimate of how many might fit on screen at a time. Taking a memory snapshot of the app after startup: Before: Heap Size: 82,899.54 KB After: Heap Size: 81,768.76 KB Which is saving about 1MB of memory on launch. In this case, it feels better to just let the `Dictionary` size itself with an estimate of what `capacity` will be.
- Loading branch information