Skip to content

Commit

Permalink
Remove allocations from OptionsCache<T> (#45229)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub authored Nov 25, 2020
1 parent f48c8d5 commit 9f6b9d1
Showing 1 changed file with 21 additions and 8 deletions.
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 _);
}
}

0 comments on commit 9f6b9d1

Please sign in to comment.