How to find the size of an object in scala?
Asked Answered
S

2

10

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

Sharma answered 2/1, 2018 at 16:37 Comment(5)
The procedure to get object sizes in Java should be equally valid in your case: #52853Clung
Possible duplicate of In Java, what is the best way to determine the size of an object?Chloromycetin
And see also #258620Chloromycetin
@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.Berna
@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.Chloromycetin
C
3

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? )

Chloromycetin answered 9/1, 2018 at 10:11 Comment(0)
P
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)
Preterition answered 28/11, 2018 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.