Frage

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

War es hilfreich?

Lösung

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 }

Andere Tipps

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top