在 scala 中获取 object/case class 的大小

get size of an object/case class in scala

我正在尝试使用 sizeEstimator 在 scala 项目中找到我的案例 class 对象的大小,但它给出了意想不到的结果。

import org.apache.spark.util.SizeEstimator
case class event(imei: String, date: String)
val check = event(imei, date)
      println("size is event obj " + SizeEstimator.estimate(check))
      println("size is single charct " + SizeEstimator.estimate("a"))
      println("size is imei " + SizeEstimator.estimate(imei))

输出为

size is event obj 520
size is single 48
size is imei 72

为什么要这么大?对于单个字符 "a" 它应该是 1 个字节,而我的 imei 是 15 个字符串值,它也应该是 15 个字节。请有任何建议。谢谢,

scala> val char:java.lang.Character = 'a'
char: Character = a

scala> SizeEstimator.estimate(char)
res18: Long = 16

scala> SizeEstimator.estimate("A")
res19: Long = 48

如果你想要实际的 Java 堆大小,你必须用 Java 类型专门声明它们,否则只用单引号是行不通的。

scala> SizeEstimator.estimate('A')
<console>:27: error: type mismatch;
 found   : Char('A')
 required: AnyRef
Note: an implicit exists from scala.Char => java.lang.Character, but
methods inherited from Object are rendered ambiguous.  This is to avoid
a blanket implicit which would convert any scala.Char to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Character`.
              SizeEstimator.estimate('A')

下面是字符串大小的计算公式-

Minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)