Use Dictionary.TryAdd instead of ContainsKey and indexer by reducing lookups. (#917)

* Use Dictionary.TryAdd instead of ContainsKey and indexer by reducing lookups.

* Update src/Markdig/Parsers/ParserList.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
prozolic
2026-01-31 06:01:27 +09:00
committed by GitHub
parent a89056d961
commit 1bac4afc9b
4 changed files with 27 additions and 11 deletions

View File

@@ -51,10 +51,7 @@ public sealed class CharacterMap<T> where T : class
{
nonAsciiMap ??= [];
if (!nonAsciiMap.ContainsKey(openingChar))
{
nonAsciiMap[openingChar] = state.Value;
}
nonAsciiMap.TryAdd(openingChar, state.Value);
}
}

View File

@@ -38,11 +38,10 @@ public abstract class ParserList<T, TState> : OrderedList<T> where T : notnull,
{
foreach (var openingChar in parser.OpeningCharacters)
{
if (!charCounter.ContainsKey(openingChar))
if (!charCounter.TryAdd(openingChar, 1))
{
charCounter[openingChar] = 0;
charCounter[openingChar]++;
}
charCounter[openingChar]++;
}
}
else

View File

@@ -0,0 +1,23 @@
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
#if !(NETSTANDARD2_1_OR_GREATER || NET)
namespace System.Collections.Generic;
internal static class DictionaryExtensions
{
public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value) where TKey : notnull
{
if (!dictionary.ContainsKey(key))
{
dictionary[key] = value;
return true;
}
return false;
}
}
#endif

View File

@@ -40,10 +40,7 @@ public class LinkReferenceDefinitionGroup : ContainerBlock
if (!Contains(link))
{
Add(link);
if (!Links.ContainsKey(label))
{
Links[label] = link;
}
Links.TryAdd(label, link);
}
}