Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
David Avatar asked May 01 '26 19:05

David


1 Answers

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();
}
like image 187
Daniel C. Sobral Avatar answered May 03 '26 18:05

Daniel C. Sobral