Skip to content

Commit

Permalink
refactor: Cache ConstructorInfo (bUnit-dev#1455)
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet authored Apr 28, 2024
1 parent fb51e5b commit 04aa5fe
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/bunit/Rendering/BunitRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
Expand All @@ -13,6 +14,7 @@ public sealed class BunitRenderer : Renderer
{
private readonly BunitServiceProvider services;
private readonly List<Task> disposalTasks = [];
private static readonly ConcurrentDictionary<Type, ConstructorInfo> componentActivatorCache = new();

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")]
private static extern ref bool GetIsBatchInProgressField(Renderer renderer);
Expand Down Expand Up @@ -214,11 +216,28 @@ protected override ComponentState CreateComponentState(int componentId, ICompone

var TComponent = component.GetType();
var renderedComponentType = typeof(RenderedComponent<>).MakeGenericType(TComponent);
var renderedComponent = Activator.CreateInstance(renderedComponentType, this, componentId, component, services, parentComponentState);
var renderedComponent = CreateComponentInstance();

Debug.Assert(renderedComponent is not null, "RenderedComponent should not be null");

return (ComponentState)renderedComponent;

object CreateComponentInstance()
{
var constructorInfo = componentActivatorCache.GetOrAdd(renderedComponentType, type
=> type.GetConstructor(
[
typeof(BunitRenderer),
typeof(int),
typeof(IComponent),
typeof(IServiceProvider),
typeof(ComponentState)
])!);

Debug.Assert(constructorInfo is not null, "Could not find ConstructorInfo");

return constructorInfo.Invoke([this, componentId, component, services, parentComponentState]);
}
}

/// <inheritdoc/>
Expand Down

0 comments on commit 04aa5fe

Please sign in to comment.