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

Reduce contention in ClockCache #7338

Merged
merged 1 commit into from
Aug 16, 2024
Merged

Reduce contention in ClockCache #7338

merged 1 commit into from
Aug 16, 2024

Conversation

benaadams
Copy link
Member

Changes

  • Reduce ClockCache contention
    • Calling ConcurrentDictionary.Count takes locks and causes contention on read side
    • Use local count that is only changed when have write lock anyway

Types of changes

What types of changes does your code introduce?

  • Optimization

Testing

Requires testing

  • No

@benaadams benaadams merged commit b18cf31 into master Aug 16, 2024
66 checks passed
@benaadams benaadams deleted the clock-cache-improves branch August 16, 2024 15:12
Copy link
Contributor

@Scooletz Scooletz left a comment

Choose a reason for hiding this comment

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

Two comments + a general one, why Count is needed at all?

@@ -21,6 +21,8 @@ public abstract class ClockCacheBase<TKey>
protected Queue<int> FreeOffsets { get; } = new();

protected int Clock { get; set; } = 0;
// Use local count to avoid lock contention with reads on ConcurrentDictionary.Count
protected int _count = 0;
Copy link
Contributor

Choose a reason for hiding this comment

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

Why introduce _count here while it's touched only by descendant classes?

@@ -131,5 +137,5 @@ public bool Contains(TKey key)
return _cacheMap.ContainsKey(key);
}

public int Count => _cacheMap.Count;
public int Count => _count;
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
public int Count => _count;
public int Count => Volatile.Read(ref _count);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants