Skip to content

[API Proposal]: ConcurrentDictionary.Clear(bool noResize) #107016

Closed
@benaadams

Description

Background and motivation

ConcurrentDictionary<TKey, TValue> allows setting the initial size; however when you call .Clear() it resets it to size 31

This is a problem if your expected size is 1 million; and it now goes through very many increasingly expensive resizes getting back to its previous size

API Proposal

namespace System.Collections.Generic;

public class ConcurrentDictionary<TKey, TValue>
{
    public void Clear(bool noResize);
}

If noResize is true it should use the current length of _tables._buckets.Length rather than HashHelpers.GetPrime(DefaultCapacity) when recreating the arrays

Tables tables = _tables;
var newTables = new Tables(new VolatileNode[HashHelpers.GetPrime(DefaultCapacity)], tables._locks, new int[tables._countPerLock.Length], tables._comparer);
_tables = newTables;
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);

API Usage

// Fancy the value
var c = new ConcurrentDictionary<long, long>(concurrencyLevel: Environment.ProcessorCount * 16, capacity: 4_000_000);


c.Clear(noResize: true);

Alternative Designs

No response

Risks

No response

Activity

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

Metadata

Assignees

No one assigned

    Labels

    area-System.CollectionsenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions