Reputation: 85
In Scala 2.10
, I create a stream, write some text into it and take its byte array:
val stream = new ByteArrayOutputStream()
// write into a stream
val ba: Array[Byte] = stream.toByteArray
I can get the number of characters using ba.length
or stream.toString().length()
. Now, how can I estimate the amount of memory taken by the data? Is it 4 (array reference) + ba.length (each array cell occupies exactly 1 byte) - and this is in bytes
?
Upvotes: 2
Views: 1684
Reputation: 12565
It occupies exactly as much memory as in java. Scala arrays are java arrays.
scala> Array[Byte](1,2,3).getClass
res1: java.lang.Class[_ <: Array[Byte]] = class [B
So the memory usage is the size of the array plus some little overhead that depends on the architecture of the machine (32 or 64bit) and the JVM.
To precisely measure the memory usage of a byte array on the JVM, you will have to use an java agent library such as JAMM.
Here is a scala project that has JAMM set up as a java agent: 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.
Here is some example code and output:
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
(This is on a 64bit linux machine using oracle java 7)
Upvotes: 10