From 2c4dfa514b479d50f17971aba749bc8e977346d3 Mon Sep 17 00:00:00 2001 From: Timothy Makkison Date: Sat, 17 Jan 2026 18:12:04 +0000 Subject: [PATCH] perf: remove closures in `GetOrAdd` --- TUnit.Core/ContextProvider.cs | 8 +++----- TUnit.Core/ObjectInitializer.cs | 5 +++-- TUnit.Core/TestContext.StateBag.cs | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/TUnit.Core/ContextProvider.cs b/TUnit.Core/ContextProvider.cs index e0e4cf0772c..8d502991a62 100644 --- a/TUnit.Core/ContextProvider.cs +++ b/TUnit.Core/ContextProvider.cs @@ -51,13 +51,11 @@ public class ContextProvider(IServiceProvider serviceProvider, string testSessio /// public AssemblyHookContext GetOrCreateAssemblyContext(Assembly assembly) { - return _assemblyContexts.GetOrAdd(assembly, asm => - { - return new AssemblyHookContext(TestSessionContext) + return _assemblyContexts.GetOrAdd(assembly, static (assembly, context) => + new AssemblyHookContext(context) { Assembly = assembly - }; - }); + }, TestSessionContext); } /// diff --git a/TUnit.Core/ObjectInitializer.cs b/TUnit.Core/ObjectInitializer.cs index a8ef5f3378c..198e499aefb 100644 --- a/TUnit.Core/ObjectInitializer.cs +++ b/TUnit.Core/ObjectInitializer.cs @@ -106,9 +106,10 @@ private static async ValueTask InitializeCoreAsync( // is called exactly once, even under contention. GetOrAdd's factory may be // called multiple times, but Lazy ensures only one initialization runs. var lazyTask = InitializationTasks.GetOrAdd(obj, - _ => new Lazy( + static (_, asyncInitializer) => new Lazy( asyncInitializer.InitializeAsync, - LazyThreadSafetyMode.ExecutionAndPublication)); + LazyThreadSafetyMode.ExecutionAndPublication) + , asyncInitializer); try { diff --git a/TUnit.Core/TestContext.StateBag.cs b/TUnit.Core/TestContext.StateBag.cs index 5d7ef3d0ac1..291b2157c93 100644 --- a/TUnit.Core/TestContext.StateBag.cs +++ b/TUnit.Core/TestContext.StateBag.cs @@ -25,7 +25,7 @@ public partial class TestContext /// T ITestStateBag.GetOrAdd(string key, Func valueFactory) { - var value = ObjectBag.GetOrAdd(key, k => valueFactory(k)!); + var value = ObjectBag.GetOrAdd(key, static (k, valueFactory) => valueFactory(k)!, valueFactory); if (value is T typedValue) {