How memory allocation occurs in scala

As we know, unlike java, scala has everything as an object.

For example, we have -

object A{ val arg1=1 def myFun(arg2:Int)=arg1 } class A{ val arg1=1 def myFun(arg2:Int)=arg1 } trait A{ val arg1=1 def myFun(arg2:Int)=arg1 } 
  • Now that everything in scala is an object, so how will the memory allocation take place?
  • Will there be all memory on the heap, except for reference variables?
  • And in java, when an instance of a class is created, the methods and variables in this class get memory on the heap. How does this happen for Singleton objects here?
  • If everything is on the heap, it will not affect performance?
  • As in Java, memory is divided into 5 sections, i.e. a bunch, a stack, a method, etc. What happens in scala, how is memory allocated?
+7
java memory-management scala memory allocation
source share
1 answer

Scala runs on the JVM and is based on the Java library.

The scala file (*. Scala ) will be compiled into the bytecode of the java class and run them in the JVM . for your example:

 object A{ val arg1=1 def myFun(arg2:Int)=arg1 } 

will be translated to (decompile bytecode by javap):

 public class A$ extends java.lang.Object{ public static final A$ MODULE$; private final int arg1; public static {}; public int arg1(); public int myFun(int); public A$(); } 

 class A{ val arg1=1 def myFun(arg2:Int)=arg1 } 

will be translated to (decompile bytecode by javap):

 public class A extends java.lang.Object{ private final int arg1; public int arg1(); public int myFun(int); public A(); } 

 trait A{ val arg1=1 def myFun(arg2:Int)=arg1 } 

will be translated to (decompile bytecode by javap):

 public interface A{ public abstract void $line5$$read$A$_setter_$arg1_$eq(int); public abstract int arg1(); public abstract int myFun(int); } 

so for your other memory issues, I think this is the same as Java .

+5
source share

All Articles