Skip to content

Commit

Permalink
perf: [Wasm] Adjust FrameworkTemplatePool to keep hard refs to pooled…
Browse files Browse the repository at this point in the history
… instances
  • Loading branch information
jeromelaban committed Mar 31, 2020
1 parent 90d0421 commit 8881200
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/Uno.UI/UI/Xaml/FrameworkTemplatePool.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using System;
#if __WASM__
#define USE_HARD_REFERENCES
#endif

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
Expand Down Expand Up @@ -83,6 +87,21 @@ public static class TraceProvider
private readonly Stopwatch _watch = new Stopwatch();
private readonly Dictionary<FrameworkTemplate, List<TemplateEntry>> _pooledInstances = new Dictionary<FrameworkTemplate, List<TemplateEntry>>(FrameworkTemplate.FrameworkTemplateEqualityComparer.Default);

#if USE_HARD_REFERENCES
/// <summary>
/// List of instances managed by the pool
/// </summary>
/// <remarks>
/// This list is required to avoid the GC to collect the instances. Othewise, the pooled instance
/// may never get its Parent property set to null, and the pool will never get notified that an instance
/// can be reused.
///
/// The root of the behavior is linked to WeakReferences to objects pending for finalizers are considered
/// null, something that does not happen on Xamarin.iOS/Android.
/// </remarks>
private readonly HashSet<UIElement> _activeInstances = new HashSet<View>();
#endif

/// <summary>
/// Determines the duration for which a pooled template stays alive.
/// </summary>
Expand Down Expand Up @@ -160,7 +179,7 @@ internal View DequeueTemplate(FrameworkTemplate template)

if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Creating new template, id={GetTemplateDebugId(template)}");
this.Log().Debug($"Creating new template, id={GetTemplateDebugId(template)} IsPoolingEnabled:{IsPoolingEnabled}");
}

instance = template.LoadContent();
Expand All @@ -187,6 +206,9 @@ internal View DequeueTemplate(FrameworkTemplate template)
}
}

#if USE_HARD_REFERENCES
_activeInstances.Add(instance);
#endif
return instance;
}

Expand Down Expand Up @@ -220,7 +242,13 @@ private void OnParentChanged(object instance, object key, DependencyObjectParent

PropagateOnTemplateReused(instance);

list.Add(new TemplateEntry(_watch.Elapsed, instance as View));
var item = instance as View;

list.Add(new TemplateEntry(_watch.Elapsed, item));

#if USE_HARD_REFERENCES
_activeInstances.Remove(item);
#endif

if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
Expand Down

0 comments on commit 8881200

Please sign in to comment.