Can this Scala code use less memory?

Consider the following Set test:

import scala.collection.immutable._

object SetTest extends App {
  def time[a](f: => a): (a,Double) = {
    val start = System.nanoTime()
    val result: a = f
    val end = System.nanoTime()
    (result, 1e-9*(end-start))
  }

  for (n <- List(1000000,10000000)) {
    println("n = %d".format(n))
    val (s2,t2) = time((Set() ++ (1 to n)).sum)
    println("sum %d, time %g".format(s2,t2))
  }
}

Compilation and launch creates

tile:scalafab% scala SetTest
n = 1000000
sum 1784293664, time 0.982045
n = 10000000
Exception in thread "Poller SunPKCS11-Darwin" java.lang.OutOfMemoryError: Java heap space
...

Ie, Scala cannot imagine a set of 10 million Ints on a machine with 8 GB of memory. Is this expected behavior? Is there a way to reduce the amount of memory?

+5
source share
3 answers

. 256 , 26 . - 60 . -J-Xmx2G , 2G, .

( , , , ).

+10

Scala, , , :

-, ( , ). , , ( , , ).

, Java - , 128 (, , , , , ).

, , - Java, . : -Xms -Xmx. :

java -Xms32m -Xmx128m MyClass   (starts MyClass with a minimum heap of 32 megabytes, maximum of 128 megabytes)

java -Xms1g -Xmx3g MyClass (executes MyClass with a minimum heap of 1 gigabytes, maximum of 3 gigabytes)

IDE, , .

+3

It should always be crowded. In this case, such large values ​​are not required. If you want the sum to use an iterator or range.

val (s2,t2) = time( (1 to n).sum)

The above line ends in a second without overflow.

You can always increase memory allocation using other answers.

-1
source

All Articles