Skip to content

Commit 7163471

Browse files
committed
Use Dictionary.TryAdd instead of ContainsKey and indexer by reducing lookups.
1 parent cd7b9ca commit 7163471

4 files changed

Lines changed: 26 additions & 12 deletions

File tree

src/Markdig/Helpers/CharacterMap.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,7 @@ public CharacterMap(IEnumerable<KeyValuePair<char, T>> maps)
5151
{
5252
nonAsciiMap ??= [];
5353

54-
if (!nonAsciiMap.ContainsKey(openingChar))
55-
{
56-
nonAsciiMap[openingChar] = state.Value;
57-
}
54+
nonAsciiMap.TryAdd(openingChar, state.Value);
5855
}
5956
}
6057

src/Markdig/Parsers/ParserList.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@ protected ParserList(IEnumerable<T> parsersArg) : base(parsersArg)
3838
{
3939
foreach (var openingChar in parser.OpeningCharacters)
4040
{
41-
if (!charCounter.ContainsKey(openingChar))
42-
{
43-
charCounter[openingChar] = 0;
44-
}
41+
charCounter.TryAdd(openingChar, 0);
4542
charCounter[openingChar]++;
4643
}
4744
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright (c) Alexandre Mutel. All rights reserved.
2+
// This file is licensed under the BSD-Clause 2 license.
3+
// See the license.txt file in the project root for more information.
4+
5+
#if !(NETSTANDARD2_1_OR_GREATER || NET)
6+
7+
namespace System.Collections.Generic;
8+
9+
internal static class DictionaryExtensions
10+
{
11+
public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value) where TKey : notnull
12+
{
13+
if (!dictionary.ContainsKey(key))
14+
{
15+
dictionary[key] = value;
16+
return true;
17+
}
18+
19+
return false;
20+
}
21+
}
22+
23+
#endif

src/Markdig/Syntax/LinkReferenceDefinitionGroup.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,7 @@ public void Set(string label, LinkReferenceDefinition link)
4040
if (!Contains(link))
4141
{
4242
Add(link);
43-
if (!Links.ContainsKey(label))
44-
{
45-
Links[label] = link;
46-
}
43+
Links.TryAdd(label, link);
4744
}
4845
}
4946

0 commit comments

Comments
 (0)