Friday, June 10, 2016

C# Hashtable vs Dictionary

June 10, 2016

Spend 2 - 3 hours to look into this topic: C# Hashmap Hashtable vs Dictionary class

Reading always helps to think deeper, and expand the knowledge. Write down notes:




Plan to go over each function in Dictionary class in C#, understand them; get familiar with Dictionary class like SQL statement, slice and dice gets easy to use Dictionary class APIs. 

Code to study:
study the code, use Dictionary class, "Sherlock and anagram" - hackerRank, 
https://gist.github.com/jianminchen/ffcca0582b5f0d1d6a9b

Solution 2:
use Dictionary class, string key for anagram string, use getHashCode() call to turn key as Int.

https://gist.github.com/jianminchen/ffcca0582b5f0d1d6a9b

Read about getHashCode() webpage:
https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx

Solution 3:
https://gist.github.com/jianminchen/8f6bd4631f0b5f0bdee7


Solution 4.
use Dictionary class, sort the key string, then anagram strings will be the same.

https://gist.github.com/jianminchen/59e326cbd1d8910c01c7

30 minutes to practice: 
study the blog: Dictionary OrderByDescending
https://goo.gl/6ZbTPz
baby step to learn C# Dictionary class API - Order by and distinct
https://gist.github.com/jianminchen/eff03bea08a95061deb4185af74fea18



Review a few of terms:

1. generic type - 
2. boxing and unboxing - Hashtable stores Object, need boxing and unboxing

3. thread safe - all memebers vs. only public static memebers
4. speed concern - Dictionary is faster than Hashtable 


Actionable items:

1. Read all dictionary classes: 

  • ConcurrentDictionary - thread safe (can be safely accessed from several threads concurrently)
  • HybridDictionary - optimized performance (for few items and also for many items)
  • OrderedDictionary - values can be accessed via int index (by order in which items were added)
  • SortedDictionary - items automatically sorted
  • StringDictionary - strongly typed and optimized for strings

Motivation talk: 

1. Julia likes to use Dictionary class instead of Hashtable, since Dictionary uses explicit type checking to match its declaration, and it is in compile time. Much better than run time Hashtable box/ unbox - type conversion. 

2. Julia likes to use Dictionary class because it is easy to complete task like order by feature. She likes to find O(N) solution to sort, but in reality, O(nlogn) is fine, just call orderBy API. 


3. Read article extension method:
Extension Methods:
https://msdn.microsoft.com/en-CA/library/bb383977.aspx




No comments:

Post a Comment