
How can you efficiently use the Clear method on the Dictionary type in your C# programs? In most cases, testing your Dictionary before taking an action on it is the best strategy. We explore this theory by seeing whether you should test for an empty Dictionary before clearing one.
This C# performance article tests the Clear method on the Dictionary type.
Collections such as the Dictionary are complex and some actions on them may be slower than you think. The Count and Clear members both seem simple, but Count is much faster than Clear. For this reason, if you may have an empty Dictionary, it is best to call Count before calling Clear. You can avoid clearing in the case where there are zero elements.
Count DictionaryProgram that tests Clear [C#]
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();
for (int i = 0; i < _max; i++)
{
dict.Clear();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
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
0.64 ns
With the Dictionary, it is faster to check for zero elements before clearing it if this case is common. Overall it seems faster to check for possible cases where no action should be taken on the Dictionary. This is also true with the indexer to add a key: it is faster to call TryGetValue or ContainsKey rather than call the indexer.
Using the Dictionary efficiently may be one of the most important optimization strategies in many C# programs. By storing data in memory, you can avoid a lot of computations, disk accesses, or even network loads. The Clear method too can be used in a more efficient way.
Collections