I'm writing some code that involves taking sets and maps with "small" (e.g., short strings or simple case classes) objects in them while recursing through a large structure, at each point adding a small (usually 1, sometimes a handful) objects to the set or map. It appears as if using mutable sets and maps gives a significant speed-up over immutable ones, but I'm having trouble quantitatively assessing the difference.
Does it make sense that Scala's garbage collection would cause a significant slow-down when I'm using immutable data structures? Would using mutable data structures fix this?
scala.collection.immutable - Immutable, sequential data-structures such as Vector , List , Range , HashMap or HashSet. scala.collection.mutable - Mutable, sequential data-structures such as ArrayBuffer , StringBuilder , HashMap or HashSet.
There are two types of collections in Scala – mutable and immutable.
A MutableList consists of a single linked list together with a pointer that refers to the terminal empty node of that list. This makes list append a constant time operation because it avoids having to traverse the list in search for its terminal node. MutableList is currently the standard implementation of mutable.
Generally, from mutable to immutable, you use the to* series methods in mutable collections, like MutableList and ListBuffer's toList method. In the other hand, from immutable to mutable, you can just use constructors like this: scala. collection.
The Scala immutable collections are surprisingly efficient. Mostly because when a structure gets changed, lots of the structure gets reused.
But if you do lots of changes mutable structures might be a better fit. Actually this is what the Scala Collection API does in many places internally: Use a mutable datastructure to build new stuff and only as a last step, create a immutable and return it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With