Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a TrieMap and what is its advantages/disadvantages compared to a HashMap?

Tags:

scala

Scala has a TrieMap collection.

What is a TrieMap and what is its advantages/disadvantages compared to a HashMap?

like image 717
Pinch Avatar asked Apr 07 '15 19:04

Pinch


2 Answers

A Scala TrieMap is a trie-based concurrent scalable map implementation. Unlike normal trie maps, a Scala TrieMap has an efficient, non-blocking, O(1) time snapshot operation (and a slightly optimized readOnlySnapshot) operation.

Absolute performance of a TrieMap is slightly below the JDK8 ConcurrentHashMap, but the advantage is that it provides consistent iterators, something that concurrent data structures typically do not have. This means that you can capture all the elements in the trie at one point in time (performance numbers and analysis here). You should use the TrieMap if you need to capture all the elements at once (e.g. to list all its elements in the UI, or to consistently analyze them).

like image 189
axel22 Avatar answered Oct 23 '22 11:10

axel22


TrieMaps are Maps using trie data structure which are essentially shallow trees. For example, If you have a 32 bit hash you break it up into sections for example 4 times 8 and at every level of the tree you branch to up to 256 sub trees. Obviously this gives O(1) performance due to the fixe size of hash(assuming few collisions).

A trie structure can be made immutable efficently, reusing the structure of a trie to create a new trie with an added or removed element. The relative performance in time/memory affect on GC depend greatly on implementation and load so rather then attempt a generic answer I would say run a benchmark. Though for a single thread with no immutability requirement a classic hashmap will normally produce better average performance and inferior worst case performance.

As a side note I will mention since the trieMap also uses a hash it is also a hashmap so I would recommend calling it a trie backed hashmap vs array backed hashmap.

like image 23
Meir Maor Avatar answered Oct 23 '22 11:10

Meir Maor