Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove allocations from OptionsCache<T> #45229

Merged
merged 1 commit into from
Nov 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,20 @@ public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
{
throw new ArgumentNullException(nameof(createOptions));
}

name = name ?? Options.DefaultName;
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
Lazy<TOptions> value;

#if NETCOREAPP
value = _cache.GetOrAdd(name, static (name, createOptions) => new Lazy<TOptions>(createOptions), createOptions);
#else
if (!_cache.TryGetValue(name, out value))
{
value = _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions));
}
#endif

return value.Value;
}

/// <summary>
Expand All @@ -50,19 +62,20 @@ public virtual bool TryAdd(string name, TOptions options)
{
throw new ArgumentNullException(nameof(options));
}
name = name ?? Options.DefaultName;
return _cache.TryAdd(name, new Lazy<TOptions>(() => options));

return _cache.TryAdd(name ?? Options.DefaultName, new Lazy<TOptions>(
#if !NETCOREAPP
() =>
#endif
options));
}

/// <summary>
/// Try to remove an options instance.
/// </summary>
/// <param name="name">The name of the options instance.</param>
/// <returns>Whether anything was removed.</returns>
public virtual bool TryRemove(string name)
{
name = name ?? Options.DefaultName;
return _cache.TryRemove(name, out Lazy<TOptions> ignored);
}
public virtual bool TryRemove(string name) =>
_cache.TryRemove(name ?? Options.DefaultName, out _);
}
}