Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary object performance

I have a possible implementation scenario where I need a dictionary object that will take 3 variables. A dialect, a query name and a query string. I should note at this stage that writing a separate class object is not an option.

My question is which of the following would perform better.

A) A single dictionary object that takes the first two variables in as a composite key e.g. "dialect,queryname" and the 3rd variable as the value.

private Dictionary<string, string>

B) A dictionary object that has another dictionary object as the value so the first variable would be the key of the primary dictionary object, the 2nd variable would be the key of the 2nd dictionary object and finally the 3rd variable would be the value of the second dictionary object.

private Dictionary<string, Dictionary<string, string>>

Seems obvious but the compiler is a mysterious thing so thought I should ask you guys.

Thanks

like image 651
CSharpened Avatar asked Jul 23 '26 15:07

CSharpened


2 Answers

Just mucking around for my own amusement ..

             Dictionary<string, string> md1 = new Dictionary<string,string>();
             Dictionary<string, Dictionary<string, string>> md2 = new Dictionary<string, Dictionary<string, string>>();

             Stopwatch st = new Stopwatch();

             st.Start(); 

             for (int i = 0; i < 2000000; i++)
             {
                 md1.Add(i.ToString(), "blabla"); 
             }

             st.Stop();

             Console.WriteLine(st.ElapsedMilliseconds);

             st.Reset();

             st.Start(); 

             for (int i = 0; i < 2000000; i++)
             {
                 md2.Add(i.ToString(), new Dictionary<string, string>()); 
             }

             st.Stop();

             Console.WriteLine(st.ElapsedMilliseconds);

             Console.ReadLine(); 

output:

831
1399
like image 107
Yorak Hunt Avatar answered Jul 25 '26 04:07

Yorak Hunt


As long as you're sure that the key "dialect,queryname" is unique, I think the first solution is faster. In the second one, you'd have to do one more dictionary lookup, which is probably more costly than a string concatenation.

like image 25
Kevin Gosse Avatar answered Jul 25 '26 04:07

Kevin Gosse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!