Warum ist ein gleichzeitiges Vermögen schneller als ein Wörterbuch in Benchmark?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Warum ist ein gleichzeitiges Vermögen schneller als ein Wörterbuch in Benchmark?

Post by Anonymous »

Ich habe einen wirklich einfachen Benchmark zum Messen und Vergleich der Leistung von Dictionary und gleichzeitiger Verfassung :

Code: Select all

[MemoryDiagnoser]
public class ExtremelySimpleDictionaryBenchmark
{
private readonly List _keys = new();
private readonly Dictionary _dict = new ();
private readonly ConcurrentDictionary _concurrentDict = new ();

private const int DictionarySize = 300;
private const string Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

private static string Generate(int length, Random random)
{
var result = new char[length];
for (var i = 0; i < length; i++)
result[i] = Alphabet[random.Next(Alphabet.Length)];
return new string(result);
}

[GlobalSetup]
public void Setup()
{
var rnd = new Random();
for (var i = 0; i < DictionarySize; i++)
{
var key = Generate(6, rnd);
var count = rnd.Next(1000);
_dict[key] = count;
_concurrentDict[key] = count;
_keys.Add(key);
}
}

[Benchmark(Baseline = true)]
public int Dictionary()
{
// variable res is used to avoid dead code elimination
var res = 0;
for (var index = 0; index < _keys.Count; index++)
if(_dict.TryGetValue(_keys[index], out var value))
res += value;
return res;
}

[Benchmark]
public int ConcurrentDictionary()
{
// variable res is used to avoid dead code elimination
var res = 0;
for (var index = 0; index < _keys.Count; index++)
if(_concurrentDict.TryGetValue(_keys[index], out var value))
res += value;
return res;
}
}
< /code>
Es führt zu wirklich seltsamen Ergebnissen. ConcurrentDictionary.trygetValue 
Beats Dictionary.tryGetValue in Bezug auf die Leistung. Ich habe die folgenden Ergebnisse: < /p>



Methode < /th>


Wörterbuch < /td>
2,055 US < /td>
-< /td>
na < /td>
< /tr>
< /tbody> < /> < /table> < /div>
< /tbody>
< /table> < /div>
bnchmark wurde auf dem banchmark .Net core 8, core 11. /> Wie können solche Ergebnisse erklärt werden? < /P>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post