Why is DenseVector a mutable collection?
Asked Answered
C

2

1

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?

Captive answered 7/11, 2016 at 20:45 Comment(0)
B
3
  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.

Bennet answered 7/11, 2016 at 21:24 Comment(3)
2. I only seems half right: Execute a=c(1,2); b=a; a[1]=0 in R, a will be 0 2 3 while b will be 1 2 3. The equivalent in Scala would be an immutable var.Captive
Although, if DenseVector would be immutable I would have to write a = a(1) := 0Captive
Yes, Breeze behaves like Numpy in this respect, rather than R or Matlab (IIRC), which can potentially end up confusing R/Matlab users as well. Again, I suspect this is a weak reason (if at all).Bennet
C
1

Performance. While functional programming provides excellent abstractions and tight code, it often doesn't offer the fastest execution. Java arrays offer far less overhead than Scala collections, and so are the go-to for highly repetitive numeric operations. Breeze DenseVectors are the same way, and are backed by java arrays under the hood.

Cimmerian answered 7/11, 2016 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.