Scala advantages of Seq.newBuilder over Seq vars

khan7 :

Currently in my application, I'm using var fooSeq: Seq[Foo] = Seq.empty and then using :+ to append items. I understand that this could lead to multithreading issues and potential race conditions, but so far have not had any issues.

I recently discovered Seq.newBuilder() and seems this might be the preferred way to use Scala sequences. I'm wondering if the performance benefit is advantageous over using vars, and any other types of benefits that it may bring

Fabián Heredia Montiel :

In general, if you are concerned with thread-safety then a common approach is to use Java's AtomicReference to wrap your mutable variable like so:

val fooSeq: AtomicReference[Seq[Foo]] = new AtomicReference(Seq.empty)

and that would be the better approach if you need intermediate results rather than going with the Builder.

If you don't need intermediate results then Builders are generally better. (Though as Luis Miguel mentions in a comment Builders are internally mutable and not necessarily thread-safe)

A third alternative is to use a mutable data structure from Scala's collections: https://docs.scala-lang.org/overviews/collections/performance-characteristics.html

You might be interested in: MutableList, however this would still need the AtomicReference wrapping for thread-safety if that is a concern. There are some data structures that are natively thread-safe like TrieMap and those are available in collections.concurrent

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398596&siteId=1