6

Is there a way to find out the memory/size occupied by an object in scala? Thanks in advance for replying me.

Pratap D
  • 221
  • 6
  • 13
  • 1
    The procedure to get object sizes in Java should be equally valid in your case: https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – Galo Navarro Jan 02 '18 at 16:50
  • Possible duplicate of [In Java, what is the best way to determine the size of an object?](https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – Rich Jan 03 '18 at 17:08
  • And see also https://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java – Rich Jan 03 '18 at 17:10
  • @Rich: Scala and Java are two completely different languages. There is absolutely no reason to assume that a solution that works for one works for the other. – Jörg W Mittag Jan 08 '18 at 20:35
  • @JörgWMittag -- I can see now that that might not be obvious to new users, thanks. I have added an answer that explains why the linked question answers this one. – Rich Jan 09 '18 at 10:11

2 Answers2

3

I also found a memory consumption estimator for Scala/Java. This library is ported from Spark project. More info here and here.

Add in sbt:

libraryDependencies += "com.madhukaraphatak" %% "java-sizeof" % "0.1"

For any object, estimate object size by calling:

SizeEstimator.estimate(obj)
Valentina
  • 409
  • 6
  • 14
2

Scala runs on the JVM, the runtime system which backs Java. A Scala object is compiled into a JVM object at runtime, and is indistinguishable from a Java object at runtime. See for example the "Scala in a Nutshell" intro at https://www.scala-lang.org/ :

SEAMLESS JAVA INTEROP

Scala runs on the JVM, so Java and Scala stacks can be freely mixed for totally seamless integration.

...

Scala classes are ultimately JVM classes. You can create Java objects, call their methods and inherit from Java classes transparently from Scala. Similarly, Java code can reference Scala classes and objects.

So for the purposes of this question, any Java answers are equally applicable to Scala.

Please refer to

(Unless you are referring to non-standard Scala runtimes like Scala.js? In that case, you should look for answers that apply to the underlying runtime, like How to get the size of a JavaScript object? )

Rich
  • 13,254
  • 1
  • 56
  • 102