Skip to content

Skip EqualityComparer<TKey>.Default creation in Dictionary .ctor - #31629

Merged
jkotas merged 2 commits into
dotnet:masterfrom
benaadams:CreateDefaultEqualityComparer-startup
Feb 3, 2020
Merged

jkotas merged 2 commits into
dotnet:masterfrom
benaadams:CreateDefaultEqualityComparer-startup

Conversation

@benaadams

@benaadams benaadams commented Feb 2, 2020 •

Copy link
Copy Markdown
Member

Saw this in startup checking if the comparer is EqualityComparer<TKey>.Default for string instantiates the static comparer, however by default the value is null; so check against null before checking the static.

e.g. in AppContext.Setup

s_dataStore = new Dictionary<string, object?>(count);

Before

image

After

image

Note it doesn't use the created comparer as it switches to NonRandomizedStringEqualityComparer

/cc @jkotas

@stephentoub

Copy link
Copy Markdown
Member

Maybe instead the ctor(int) overload shouldn't delegate to the ctor(int, comparer) overload at all?

@benaadams

Copy link
Copy Markdown
Member Author

Maybe instead the ctor(int) overload shouldn't delegate to the ctor(int, comparer) overload at all?

For string when its null it then runs this test and sets it to NonRandomizedStringEqualityComparer.Default which is why its manly problematic:

if (typeof(TKey) == typeof(string) && _comparer == null)
{
	// To start, move off default comparer for string which is randomised
	_comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}

Other types would use the default comparer when null, but string sets it to something else (to move off the randomized path to begin with)

@stephentoub

stephentoub commented Feb 2, 2020 •

Copy link
Copy Markdown
Member

Sure, so the ctor would just do:

if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);

if (capacity > 0) Initialize(capacity);

if (typeof(TKey) == typeof(string))
{
       _comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}

No? Maybe it's not better, just making sure we considered it.

@stephentoub

Copy link
Copy Markdown
Member

Meh, what you have is probably better.

@benaadams

Copy link
Copy Markdown
Member Author

Was mostly thinking about generic instantiation size; otherwise having the second .ctor would be better

@jkotas

jkotas commented Feb 3, 2020

Copy link
Copy Markdown
Member

The failures are known issue (looks like a bad PR got merged).

@jkotas
jkotas merged commit fb14ae8 into dotnet:master Feb 3, 2020
@benaadams
benaadams deleted the CreateDefaultEqualityComparer-startup branch February 3, 2020 05:05
@ghost ghost locked as resolved and limited conversation to collaborators Dec 10, 2020
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.

4 participants