A faster way to create a nullified array in Scala

I am creating nullified arrays in Scala with (0 until Nrows).map (_ => 0).toArraybut is there anything faster? mapslow.

I have the same question, but with 1 instead of O, that is, I also want to speed up (0 until Nrows).map (_ => 1).toArray

+4
source share
2 answers

Zero is the default value for the Ints array, so just do the following:

    val array = new Array[Int](NRows)

If you want all of these values ​​to be 1 s, use .fill () (thanks to @gourlaysama):

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

However, looking at how this works internally, it involves creating a few objects that you don't need. I suspect that the following (ugly) approach may be faster if speed is your main problem:

    val array = new Array[Int](NRows)
    for (i <- 0 until array.length) { array(i) = 1 }
+9

Array.ofDim, ,

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))

,

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

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

(, ) Array.tabulate, ,

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)
+6

Source: https://habr.com/ru/post/1540379/


All Articles