Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how do immutable and mutable sets and maps compare with regard to garbage collection?

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?

like image 327
Omer Zach Avatar asked Oct 16 '12 02:10

Omer Zach


People also ask

What is Scala collection mutable map?

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.

What are the collections in Scala?

There are two types of collections in Scala – mutable and immutable.

What is mutable list in Scala?

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.

How can we convert mutable to immutable Scala?

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.


1 Answers

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.

like image 61
Jens Schauder Avatar answered Sep 24 '22 20:09

Jens Schauder