Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Difference between Dictionary, Hashtable and Map

Tags:

I am new to .NET programming. Sorry if this question has been asked before.

I am currently learning F#. What are the differences between Dictionary, Hashtable and Map? When should I use each?

I also have another question that is not mentioned in the title. When should I use Async.RunSynchronously? It seems rather self-contradictory to me, so I am sure that I am missing something.

like image 780
M.Y. Babt Avatar asked Mar 16 '15 12:03

M.Y. Babt


1 Answers

The choice between Dictionary, Hashtable and Map depends on the uses cases. You should however know the characteristics of each. This is not an exhaustive list but just some key differences you might want to start from :

  • Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key. This is a mutable collection from .NET BCL
  • Dictionary<> this is a generic implementation of the hashtable. Also a mutable collection from .NET BCL
  • Map This is the F# immutable type. It is implemented based on AVL trees which is an entirely different data structure with different performance characteristics and use cases.

If you are doing many writes, Hash tables collections have significantly better fill rate performance than AVL trees.

Retrieving a value from a Dictionary by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.

F# maps are implemented as immutable AVL trees, an efficient data structure which forms a self-balancing binary tree. AVL trees are well-known for their efficiency, in which they can search, insert, and delete elements in the tree in O(log n) time, where n is the number of elements in the tree.

As for the map uses case, if you’ve got a set of sta­tic data (such as con­fig­u­ra­tion data that’s loaded when your appli­ca­tion starts up) you need to look up by key fre­quently, a Map is as good a choice as any, its immutabil­ity in this case ensures that the sta­tic data can­not be mod­i­fied by mis­take and has lit­tle impact to per­for­mance as you never need to mutate it once initialized.

Async.RunSynchronously runs the provided asynchronous computation and awaits its result. You can use it in F# interactive window for example to test your asynchronous workflows.

like image 103
Tomasz Jaskuλa Avatar answered Sep 25 '22 12:09

Tomasz Jaskuλa