问题
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?
回答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 anImmutableArray
which wraps anArray
, but this would force some operations which can avoid copies by being in-place to copy, maybe interact weirdly with specialization, etc.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.
回答2:
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 DenseVector
s are the same way, and are backed by java arrays under the hood.
来源:https://stackoverflow.com/questions/40474293/why-is-densevector-a-mutable-collection