Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to make a zeroed array in Scala

Tags:

arrays

scala

I create zeroed Arrays in Scala with (0 until Nrows).map (_ => 0).toArray but is there anything faster ? map is slow.

I have the same question but with 1 instead of O, i.e. I also want to accelerate (0 until Nrows).map (_ => 1).toArray

like image 915
user2987828 Avatar asked Dec 07 '22 02:12

user2987828


2 Answers

Zero is the default value for an array of Ints, so just do this:

    val array = new Array[Int](NRows)

If you want all those values to be 1s then use .fill() (with thanks to @gourlaysama):

    val array = Array.fill(NRows)(1)

However, looking at how this works internally, it involves the creation of a few objects that you don't need. I suspect the following (uglier) approach may be quicker if speed is your main concern:

    val array = new Array[Int](NRows)
    for (i <- 0 until array.length) { array(i) = 1 }
like image 140
chrisloy Avatar answered Dec 29 '22 01:12

chrisloy


For multidimensional arrays consider Array.ofDim, for instance,

scala> val a = Array.ofDim[Int](3,3)
a: Array[Array[Int]] = Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))

Likewise,

scala> val a = Array.ofDim[Int](3)
a: Array[Int] = Array(0, 0, 0)

In the context here,

val a = Array.ofDim[Int](NRows)

For setting (possibly nonzero) initial values, consider Array.tabulate, for instance,

scala> Array.tabulate(3,3)( (x,y) => 1)
res5: Array[Array[Int]] = Array(Array(1, 1, 1), Array(1, 1, 1), Array(1, 1, 1))

scala> Array.tabulate(3)( x => 1)
res18: Array[Int] = Array(1, 1, 1)
like image 33
elm Avatar answered Dec 28 '22 23:12

elm