Array[Byte] 在 Scala 中占用多少内存?
How much memory does Array[Byte] occupy in Scala?
在 Scala 2.10
中,我创建了一个流,将一些文本写入其中并获取其字节数组:
val stream = new ByteArrayOutputStream()
// write into a stream
val ba: Array[Byte] = stream.toByteArray
我可以使用 ba.length
或 stream.toString().length()
获取字符数。现在,我如何估计数据占用的内存量?是4 (array reference) + ba.length (each array cell occupies exactly 1 byte) - and this is in bytes
吗?
它占用的内存与 java 中一样多。 Scala 数组 是 java 数组。
scala> Array[Byte](1,2,3).getClass
res1: java.lang.Class[_ <: Array[Byte]] = class [B
所以内存使用量是数组的大小加上一些小的开销,这取决于机器的体系结构(32 位或 64 位)和 JVM。
要精确测量 JVM 上字节数组的内存使用情况,您将不得不使用 java 代理库,例如 JAMM.
这是一个将 JAMM 设置为 java 代理的 Scala 项目:https://github.com/rklaehn/scalamuc_20150707 . The build sbt shows how to configure JAMM as an agent for an sbt project, and there are some example tests here.
下面是一些示例代码和输出:
val mm = new MemoryMeter()
val test = Array.ofDim[Byte](100)
println(s"A byte array of size ${test.length} uses "+ mm.measure(test) + "bytes");
> A byte array of size 100 uses 120 bytes
(这是在 64 位 linux 机器上使用 oracle java 7)
在 Scala 2.10
中,我创建了一个流,将一些文本写入其中并获取其字节数组:
val stream = new ByteArrayOutputStream()
// write into a stream
val ba: Array[Byte] = stream.toByteArray
我可以使用 ba.length
或 stream.toString().length()
获取字符数。现在,我如何估计数据占用的内存量?是4 (array reference) + ba.length (each array cell occupies exactly 1 byte) - and this is in bytes
吗?
它占用的内存与 java 中一样多。 Scala 数组 是 java 数组。
scala> Array[Byte](1,2,3).getClass
res1: java.lang.Class[_ <: Array[Byte]] = class [B
所以内存使用量是数组的大小加上一些小的开销,这取决于机器的体系结构(32 位或 64 位)和 JVM。
要精确测量 JVM 上字节数组的内存使用情况,您将不得不使用 java 代理库,例如 JAMM.
这是一个将 JAMM 设置为 java 代理的 Scala 项目:https://github.com/rklaehn/scalamuc_20150707 . The build sbt shows how to configure JAMM as an agent for an sbt project, and there are some example tests here.
下面是一些示例代码和输出:
val mm = new MemoryMeter()
val test = Array.ofDim[Byte](100)
println(s"A byte array of size ${test.length} uses "+ mm.measure(test) + "bytes");
> A byte array of size 100 uses 120 bytes
(这是在 64 位 linux 机器上使用 oracle java 7)