Skip to content

Conversation

@StephenMolloy
Copy link
Member

Reduce unnecessary allocation of SeldomUsedFields in MemoryCache.

Checking for the existence of a 'seldom used field' would trigger
the allocation of this object, even if none of the fields were being
used. And this check/trigger happens on just about every item
inserted in the cache, meaning this perf optimization wasn't actually
saving anything. The fix is to not allocate when simply checking
for the existence of these fields.

Fix #1425

// is never null. So check that the collection of dependencies is not empty before allocating
// the 'seldom' used fields.
if (dependencies != null && dependencies.Count > 0)
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's a bug here. The dependencies param passed originally comes from CacheItemPolicy.ChangeMonitors. The docs for that property says:

If you change the set of change monitors on a CacheItemPolicy object after the CacheItemPolicy object has been passed to an ObjectCache implementation, the changes have no effect.

This implies that the dependencies are expected to be copied when passed in. If a caller passes a CacheItemPolicy to MemoryCache.Set, and then modifies the CacheItemPolicy.ChangeMonitors collection afterwards, that change will be reflected in the collection stored here. It's also not thread safe. For example, CallNotifyOnChanged gets an iterator which will throw if the collection is modified while iterating.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch @mconnew. That issue has been present since NetFx days and quite frankly won't change in NetFx. I've opened a new issue for it here. #52033

As far as this SeldomUsedFields fix goes... it looks fine?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, for the scope of this fix, it looks good.

Co-authored-by: Christopher Watford <[email protected]>
@StephenMolloy StephenMolloy merged commit 430e424 into dotnet:main May 6, 2021
@karelz karelz added this to the 6.0.0 milestone May 20, 2021
@ghost ghost locked as resolved and limited conversation to collaborators Jun 19, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MemoryCache use of seldom used fields

4 participants