Search code examples
optimizationscalatypesprimitive

Scala "primitive" optimisation


In several places I have seen a declaration similar to:

"The Scala compiler uses Java arrays, primitive types, and native arithmetic where possible in the compiled code" (Programming in Scala book). But in practise I am not seeing this, for example in the following code, the scala type is using more memory than the java type (which I calculated by using the totalMemory and freeMemory methods):

long[] la = new Array[java.lang.Long](1024 * 1024);
for(i <- 0 until la.length)
  la(i) = new java.lang.Long(0);

val La = new Array[Long](1024 * 1024);
for(i <- 0 until La.length)
  La(i) = 0l;

mem_used (java long):>> 28.811M

mem_used (scala long):>> 36.811M

I realise the scala Any type has additional overhead, but where is the optimisation happening?


Solution

  • Why bother with such a convoluted way of trying to find out what gets compiled to what? Just run javap on a class and you'll see exactly what it is.

    C:\>type La.scala
    class La {
        val La = new Array[Long](1024 * 1024);
    }
    
    C:\>javap La
    Compiled from "La.scala"
    public class La extends java.lang.Object implements scala.ScalaObject{
        public long[] La();
        public La();
    }