Fastest way to take elementwise sum of two Lists

后端 未结 1 1647
情深已故
情深已故 2021-01-02 19:15

I can do elementwise operation like sum using Zipped function. Let I have two Lists L1 and L2 as shown below



        
相关标签:
1条回答
  • 2021-01-02 20:02

    One option would be to use a Streaming implementation, taking advantage of the lazyness may increase the performance.

    An example using LazyList (introduced in Scala 2.13).

    def usingLazyList(l1: LazyList[Double], l2: LazyList[Double], l3: LazyList[Double]): LazyList[Double] =
      ((l1 zip l2) zip l3).map {
        case ((a, b), c) =>
          ((a + b) * math.random()) + c
      }
    

    And an example using fs2.Stream (introduced by the fs2 library).

    import fs2.Stream
    import cats.effect.IO
    
    def usingFs2Stream(s1: Stream[IO, Double], s2: Stream[IO, Double], s3: Stream[IO, Double]): Stream[IO, Double] =
      s1.zipWith(s2) {
        case (a, b) =>
          (a + b) * math.random()
      }.zipWith(s3) {
        case (acc, c) =>
          acc + c
      }
    

    However, if those are still too slow, the best alternative would be to use plain arrays.

    Here is an example using ArraySeq (introduced in Scala 2.13 too) which at least will preserve immutability. You may use raw arrays if you prefer but take care.
    (if you want, you may also use the collections-parallel module to be even more performant)

    import scala.collection.immutable.ArraySeq
    import scala.collection.parallel.CollectionConverters._
    
    def usingArraySeq(a1: ArraySeq[Double], a2: ArraySeq[Double], a3: ArraySeq[Double]): ArraySeq[Double] = {
      val length = a1.length
    
      val arr = Array.ofDim[Double](length)
    
      (0 until length).par.foreach { i =>
        arr(i) = ((a1(i) + a2(i)) * math.random()) + a3(i)
      }
    
      ArraySeq.unsafeWrapArray(arr)
    }
    
    0 讨论(0)
提交回复
热议问题