Skip to content

Commit 9f6b9d1

Browse files
authored
Remove allocations from OptionsCache<T> (#45229)
1 parent f48c8d5 commit 9f6b9d1

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,20 @@ public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
3434
{
3535
throw new ArgumentNullException(nameof(createOptions));
3636
}
37+
3738
name = name ?? Options.DefaultName;
38-
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
39+
Lazy<TOptions> value;
40+
41+
#if NETCOREAPP
42+
value = _cache.GetOrAdd(name, static (name, createOptions) => new Lazy<TOptions>(createOptions), createOptions);
43+
#else
44+
if (!_cache.TryGetValue(name, out value))
45+
{
46+
value = _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions));
47+
}
48+
#endif
49+
50+
return value.Value;
3951
}
4052

4153
/// <summary>
@@ -50,19 +62,20 @@ public virtual bool TryAdd(string name, TOptions options)
5062
{
5163
throw new ArgumentNullException(nameof(options));
5264
}
53-
name = name ?? Options.DefaultName;
54-
return _cache.TryAdd(name, new Lazy<TOptions>(() => options));
65+
66+
return _cache.TryAdd(name ?? Options.DefaultName, new Lazy<TOptions>(
67+
#if !NETCOREAPP
68+
() =>
69+
#endif
70+
options));
5571
}
5672

5773
/// <summary>
5874
/// Try to remove an options instance.
5975
/// </summary>
6076
/// <param name="name">The name of the options instance.</param>
6177
/// <returns>Whether anything was removed.</returns>
62-
public virtual bool TryRemove(string name)
63-
{
64-
name = name ?? Options.DefaultName;
65-
return _cache.TryRemove(name, out Lazy<TOptions> ignored);
66-
}
78+
public virtual bool TryRemove(string name) =>
79+
_cache.TryRemove(name ?? Options.DefaultName, out _);
6780
}
6881
}

0 commit comments

Comments
 (0)