How much memory does Array[Byte] occupy in Scala? -


in scala 2.10, create stream, write text , take byte array:

val stream = new bytearrayoutputstream() // write stream val ba: array[byte] = stream.tobytearray 

i can number of characters using ba.length or stream.tostring().length(). now, how can estimate amount of memory taken data? 4 (array reference) + ba.length (each array cell occupies 1 byte) - , in bytes?

it occupies memory in java. scala arrays are java arrays.

scala> array[byte](1,2,3).getclass res1: java.lang.class[_ <: array[byte]] = class [b 

so memory usage size of array plus little overhead depends on architecture of machine (32 or 64bit) , jvm.

to precisely measure memory usage of byte array on jvm, have use java agent library such jamm.

here scala project has jamm set java agent: https://github.com/rklaehn/scalamuc_20150707 . build sbt shows how configure jamm agent sbt project, , there example tests here.

here example code , 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");  > byte array of size 100 uses 120 bytes 

(this on 64bit linux machine using oracle java 7)


Comments