From 91be36d1f1d25e3a2493f9b53973b3e5dc191ad5 Mon Sep 17 00:00:00 2001 From: Ramez Ragaa Date: Thu, 17 Oct 2024 18:42:25 +0300 Subject: [PATCH] perf: optimize opacity filter allocations --- .../Composition/Uno/DrawingFilter.skia.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Uno.UI.Composition/Composition/Uno/DrawingFilter.skia.cs b/src/Uno.UI.Composition/Composition/Uno/DrawingFilter.skia.cs index 89e0de6af019..ceecb4af8699 100644 --- a/src/Uno.UI.Composition/Composition/Uno/DrawingFilter.skia.cs +++ b/src/Uno.UI.Composition/Composition/Uno/DrawingFilter.skia.cs @@ -3,6 +3,7 @@ using System; using System.Linq; using SkiaSharp; +using Uno.Extensions; namespace Uno.UI.Composition; @@ -13,15 +14,21 @@ namespace Uno.UI.Composition; /// The opacity to apply to children. /// This should be applied only on drawing and not the container to avoid fade-ou of child containers. /// -internal record struct DrawingFilters(float Opacity) +internal readonly record struct DrawingFilters(float Opacity) { public static DrawingFilters Default { get; } = new(1.0f); - private SKColorFilter? _opacityColorFilter = null; - // Note: This SKColorFilter might be created more than once since this Filter is a struct. // However since this Filter is copied (pushed to the stack) only when something changes, it should still catch most cases. public SKColorFilter? OpacityColorFilter => Opacity is 1.0f ? null - : _opacityColorFilter ??= SKColorFilter.CreateBlendMode(new SKColor(0xFF, 0xFF, 0xFF, (byte)(255 * Opacity)), SKBlendMode.Modulate); + : _opacityToColorFilter.Invoke((byte)(255 * Opacity)); + + // only 255 possible values + private static readonly Func _opacityToColorFilter = FuncMemoizeExtensions.AsMemoized((byte opacity) + => + { + Console.WriteLine($"Ramez created a new color filter for opacity {opacity}"); + return SKColorFilter.CreateBlendMode(new SKColor(0xFF, 0xFF, 0xFF, opacity), SKBlendMode.Modulate); + }); }