C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# program that clears Dictionary contents
using System.Collections.Generic;
using static System.Console;
class Program
{
static void Main()
{
// Create a small dictionary.
// ... Add 2 keys.
var lookup = new Dictionary<string, int>();
lookup["cat"] = 10;
lookup["dog"] = 20;
// Write the count.
WriteLine(lookup.Count);
// Clear the dictionary and write its new count.
lookup.Clear();
WriteLine(lookup.Count);
}
}
Output
2
0
Version 1: This version of the code calls Clear each time through the inner loop. We compute the average amount of time.
BenchmarkStopwatchVersion 2: This code uses Clear but only when there are 1 or more elements in the Dictionary. So it can avoid calling Clear.
Result: Version 2 is faster. If you may have an empty Dictionary, it is best to call Count before calling Clear.
C# program that times Clear
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
var dict = new Dictionary<string, string>();
var s1 = Stopwatch.StartNew();
// Version 1: use Clear.
for (int i = 0; i < _max; i++)
{
dict.Clear();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use Clear if needed.
for (int i = 0; i < _max; i++)
{
if (dict.Count > 0)
{
dict.Clear();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
3.17 ns Always call Clear
0.64 ns Call Clear if Count > 0
And: This is also true with the indexer to add a key: it is faster to call TryGetValue or ContainsKey rather than call the indexer.
IndexerTryGetValueContainsKey