class Program
{
static Dictionary<string, int> Dictionary = new Dictionary<string, int>();
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Thread[] threads = new Thread[500];
for(int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(InsertAlphabet);
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
Console.WriteLine(Dictionary.Count);
Console.WriteLine(stopwatch.ElapsedMilliseconds);
foreach (KeyValuePair<string,int> kvp in Dictionary)
{
Console.WriteLine(kvp.Key + " " + kvp.Value);
}
stopwatch.Stop();
Console.ReadLine();
}
private static void InsertAlphabet()
{
string[] alphabetArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
foreach (var alphabet in alphabetArray)
{
Add(alphabet);
}
}
public static void Add(string bar)
{
lock (Dictionary)
{
if (!Dictionary.ContainsKey(bar))
{
Dictionary.Add(bar, 1);
}
else
{
Dictionary[bar] += 1;
}
}
}
}
I have created this simple console application to make sure that the data inserted into the dictionary is accurate.
The time that I took to insert the alphabets as key and the count as the value was approximately 3 seconds for 500 threads trying to insert at the same time.
Is there a way I can improve the performance of this by having some kind of approximation involved (data doesn't need to be 100% accurate. Allowed accuracy 95%).
Also are there suggestions on how can I improve the increment of count in the dictionary.