TCX
TCX

Reputation: 31

Why is Scala slow to initialize an Array of tuples?

This is the slow code

object Hello {
  def main(args: Array[String]) = {
    val ret = Array.fill[(Int, Int, Int)](8000000){(0, 0, 0)}
    println(ret.size)
  }
}

It runs for 2 minutes. And then outputs

java.lang.OutOfMemoryError: GC overhead limit exceeded

And this is the fast code

object Hello {
  def main(args: Array[String]) = {
    val ret = Array.fill[Int](24000000){0}
    println(ret.size)
  }
}

It runs for 0.5 seconds.

My compilation option:

scalac Hello.scala

Why is there a huge gap?

Upvotes: 2

Views: 171

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

Array[Int] is an array of primitives.

Array[(Int, Int, Int)] is an array of objects.

(You can experiment with Array[java.lang.Integer], which is an array of objects too.)


Something's with your settings, normally

object Hello {
  def main(args: Array[String]) = {
    val ret = Array.fill[(Int, Int, Int)](8000000){(0, 0, 0)}
    println(ret.size)
  }
}

doesn't take long https://scastie.scala-lang.org/4p4GpYbHSqm7K6U3hwLdYw

Upvotes: 3

Related Questions