Adding immutable vectors

I am trying to work more with an immutable scalas collection, as it is easy to parallelize, but I am struggling with some newbie problems. I am looking for a way to create a (efficiently) new vector from an operation. To be precise, I want something like

val v : Vector[Double] = RandomVector(10000)
val w : Vector[Double] = RandomVector(10000)
val r = v + w

I tested the following:

// 1)
val r : Vector[Double] = (v.zip(w)).map{ t:(Double,Double) => t._1 + t._2 }

// 2)
val vb = new VectorBuilder[Double]()    
var i=0
while(i<v.length){
  vb += v(i) + w(i)
  i = i + 1
}
val r = vb.result

}

Both are very long compared to working with an array:

[Vector Zip/Map   ] Elapsed time 0.409 msecs
[Vector While Loop] Elapsed time 0.374 msecs
[Array While Loop ] Elapsed time 0.056 msecs
// with warm-up (10000) and avg. over 10000 runs

Is there a better way to do this? I think that working with zip / map / reduce has the advantage that it can work in parallel as soon as collections support this.

thank

+3
source share
3 answers

Vector Double, . , , , , Vector ( 12 + ). , , , , scala.actors.Futures.future , :

val a = Array(1,2,3,4,5,6,7,8)
(0 to 4).map(_ * (a.length/4)).sliding(2).map(i => scala.actors.Futures.future {
  var s = 0
  var j = i(0)
  while (j < i(1)) {
    s += a(j)
    j += 1
  }
  s
}).map(_()).sum  // _() applies the future--blocks until it done

, ( ) , .

+5

, :

v1.view zip v2 map { case (a,b) => a+b }

, , .

, , , .

+4

Arrays are not erased by type, vectors. In principle, the JVM gives an advantage Arrayover other collections when processing primitives that cannot be overcome. Scala specializationcan reduce this advantage, but given their cost in code size, they cannot be used universally.

+4
source

All Articles