Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is performance of ContainsKey and TryGetValue?

I'm prepping for interviews, and some obvious interview questions such as counting frequency of characters in a string involve putting all of the characters into a Hashtable/Dictionary in order to get O(n) runtime for the algorithm. My question is, what is the performance hit by using ContainsKey and TryGetValue to check to see if a key has already been inserted into the Hashtable? Can I still have an O(n) algorithm for problems like these that use ContainsKey or TryGetValue?

like image 322
alexD Avatar asked Aug 04 '11 18:08

alexD


People also ask

What does TryGetValue do?

This method optimizes Dictionary usage. It gets a value (at a key) from a Dictionary. And it eliminates unneeded lookups, making programs better.

Is Dictionary TryGetValue thread safe?

a) This is not thread-safe, as the underlying Dictionary itself is not thread safe. If another thread is calling Add at the same time, undefined behavior can occur.

What is ContainsKey C#?

ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not. Declare a Dictionary and add elements − var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} };

Can TryGetValue return null?

The most it can say is that if TryGetValue returns false, and if the type argument in question is a reference type or a nullable value, then the result will be null.


1 Answers

Assuming a good hash without too many collisions, each of those are O(1) operations.

As for how those operations work... I suggest you read up on hash tables.

like image 164
Jon Skeet Avatar answered Oct 17 '22 02:10

Jon Skeet