I have written some Scala code to perform an element-wise
operation on a collection. Here I defined two methods that perform the same task. One
method uses zip
and the other uses
zipped
.
def
ES (arr :Array[Double], arr1 :Array[Double]) :Array[Double] = arr.zip(arr1).map(x =>
x._1 + x._2)
def ES1(arr :Array[Double], arr1 :Array[Double])
:Array[Double] = (arr,arr1).zipped.map((x,y) => x +
y)
To
compare these two methods in terms of speed, I wrote the following
code:
def fun (arr : Array[Double]
, arr1 : Array[Double] , f :(Array[Double],Array[Double]) => Array[Double] , itr :
Int) ={
val t0 = System.nanoTime()
for (i <- 1 to itr)
{
f(arr,arr1)
}
val t1 = System.nanoTime()
println("Total Time Consumed:" + ((t1 - t0).toDouble / 1000000000).toDouble +
"Seconds")
}
I
call the fun
method and pass ES
and
ES1
as
below:
fun(Array.fill(10000)(math.random),
Array.fill(10000)(math.random), ES ,
100000)
fun(Array.fill(10000)(math.random), Array.fill(10000)(math.random),
ES1, 100000)
The
results show that the method named ES1
that uses
zipped
is faster than method ES
that
uses zip
.
Based on these observations, I
have two questions.
Why is
zipped
faster than
zip
?
Is there any even
faster way to do element-wise operations on a collection in
Scala?
No comments:
Post a Comment