Make42 Make42 - 11 months ago 86
Scala Question

Why is DenseVector a mutable collection?

Usually (so far always) I try to use immutable collection in Scala, especially so that if I give a reference to a collection to some other part of my program I cannot override the original source by accident. Using breeze, I would like to know: Why was it decided to have DenseVector be a mutable collection?

Is this just a (maybe unwanted) side effect of using in Arrays in the background? If so, why were Arrays used, instead of another (immutable) collection?

Answer Source
  1. Performance.

    Breeze uses netlib-java for its core linear algebra routines. This includes all the cubic time operations, matrix-matrix and matrix-vector multiplication. Special efforts are taken to ensure that arrays are not copied.

    A DenseVector backed by anything other than an array would be substantially slower. It could wrap an ImmutableArray which wraps an Array, but this would force some operations which can avoid copies by being in-place to copy, maybe interact weirdly with specialization, etc.

  2. I don't know how important this is (I suspect not much), but for people coming to Breeze from numerical computing (instead of from Scala) mutability is expected. E.g. it makes it simpler to port an algorithm which is implemented in Matlab or in R to Breeze.