Skip to content

Commit

Permalink
Avoid boxing in System.ObjectModel.KeydCollection during startup
Browse files Browse the repository at this point in the history
ArgumentNullException.ThrowIfNull can incur boxing when applied to argument
of generic type. Tier-1 JIT optimizations are able to optimize this boxing
in steady state, but Tier-0 JIT optimization are not. It can result into excessive
allocations during startup. Switch KeyedCollection to use ThrowHelper
that is pattern used by number of other collections.
  • Loading branch information
jkotas committed Jul 6, 2024
1 parent ceac9f4 commit ccc9e23
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<Compile Include="System.ObjectModel.Forwards.cs" />
<Compile Include="System\ThrowHelper.cs" />
<Compile Include="System\Collections\CollectionHelpers.cs" />
<Compile Include="System\Collections\Generic\DebugView.cs" />
<Compile Include="System\Collections\Specialized\INotifyCollectionChanged.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ public TItem this[TKey key]

public bool Contains(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(key));
}

if (dict != null)
{
Expand All @@ -91,7 +94,10 @@ public bool Contains(TKey key)

public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TItem item)
{
ArgumentNullException.ThrowIfNull(key);
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(key));
}

if (dict != null)
{
Expand Down Expand Up @@ -131,7 +137,10 @@ private bool ContainsItem(TItem item)

public bool Remove(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(key));
}

if (dict != null)
{
Expand Down
14 changes: 14 additions & 0 deletions src/libraries/System.ObjectModel/src/System/ThrowHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;

namespace System
{
internal static class ThrowHelper
{
[DoesNotReturn]
public static void ThrowArgumentNullException(string? paramName) =>
throw new ArgumentNullException(paramName);
}
}

0 comments on commit ccc9e23

Please sign in to comment.