Skip to content

Commit

Permalink
✨ Add a cache to the filename to BitmapImage converter.
Browse files Browse the repository at this point in the history
I noticed that the filename property would be read multiple times in succession on the same instance. This should at least make this scenario less heavy on resources. This can be improved later on to have some kind of minimum retention timer for images, in order to mitigate the potentially too efficient GC. (If needed)
  • Loading branch information
hexawyz committed Jan 17, 2025
1 parent afa44c0 commit 1724cb9
Showing 1 changed file with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;

namespace Exo.Settings.Ui.Converters;

internal sealed class FileNameToBitmapImageConverter : IValueConverter
{
private readonly Dictionary<string, WeakReference<BitmapImage>> _bitmapCache = new(StringComparer.OrdinalIgnoreCase);

public object? Convert(object value, Type targetType, object parameter, string language)
{
if (value is not string fileName) return null;

var bitmapImage = new BitmapImage();
// In this case, we take the bet that the filename and the file will "always" be valid. As such, we pre-allocate a weak reference before knowing if the file will be read successfully.
BitmapImage? bitmapImage;
if (_bitmapCache.TryGetValue(fileName, out var wr))
{
if (wr.TryGetTarget(out bitmapImage)) return bitmapImage;
bitmapImage = new();
wr.SetTarget(bitmapImage);
}
else
{
bitmapImage = new();
_bitmapCache.Add(fileName, new(bitmapImage, false));
}

LoadImage(bitmapImage, fileName);
return bitmapImage;
}
Expand Down

0 comments on commit 1724cb9

Please sign in to comment.