Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala + Java serialization size
import java.io._
def sizeOf[T](x:T, y:T): (Long, Long) = {
val buf = new ByteArrayOutputStream
val oos = new ObjectOutputStream(buf)
oos.writeObject(x)
val initSize = buf.size
oos.writeObject(y)
val size = buf.size - initSize
oos.close
(initSize, size)
}
// null vs None
scala> sizeOf(null, null)
res0: (Long, Long) = (5,1)
scala> sizeOf(None, None)
res1: (Long, Long) = (59,5)
// null vs None, inside object
scala> case class NullWrapper(x: String, y: Int)
defined class NullWrapper
scala> sizeOf(NullWrapper(null, 1), NullWrapper(null, 2))
res1: (Long, Long) = (95,11)
scala> case class NoneWrapper(x: Option[String], y: Int)
defined class NoneWrapper
scala> sizeOf(NoneWrapper(None, 1), NoneWrapper(None, 2))
res2: (Long, Long) = (145,15)
scala> sizeOf((None, 1), (None, 2))
res4: (Long, Long) = (201,21)
scala> sizeOf((null, 1), (null, 2))
res5: (Long, Long) = (147,17)
// overhead of Some
scala> sizeOf("hi", "ho")
res2: (Long, Long) = (9,5)
scala> sizeOf(Some("hi"), Some("ho"))
res12: (Long, Long) = (88,11)
// [Int] Seq vs List vs Vector vs Array vs Tuple
scala> sizeOf(Seq(1, 2, 3), Seq(4, 5, 6))
res13: (Long, Long) = (230,42)
scala> sizeOf(List(1, 2, 3), List(4, 5, 6))
res14: (Long, Long) = (230,42)
scala> sizeOf(Vector(1, 2, 3), Vector(4, 5, 6))
res15: (Long, Long) = (403,97)
scala> sizeOf(Array(1, 2, 3), Array(4, 5, 6))
res16: (Long, Long) = (39,22)
scala> sizeOf((1, 2, 3), (4, 5, 6))
res17: (Long, Long) = (176,36)
// [String] Seq vs List vs Vector vs Array vs Tuple
scala> sizeOf(Seq("a", "b", "c"), Seq("d", "e", "f"))
res18: (Long, Long) = (145,24)
scala> sizeOf(List("a", "b", "c"), List("d", "e", "f"))
res19: (Long, Long) = (145,24)
scala> sizeOf(Vector("a", "b", "c"), Vector("d", "e", "f"))
res20: (Long, Long) = (318,79)
scala> sizeOf(Array("a", "b", "c"), Array("d", "e", "f"))
res21: (Long, Long) = (56,22)
scala> sizeOf(("a","b","c"), ("d","e","f"))
res22: (Long, Long) = (91,18)
// Tuple vs case class
scala> sizeOf((1, "a"), (2, "b"))
res23: (Long, Long) = (150,20)
scala> case class Wrapper(a: Int, b: String)
defined class Wrapper
scala> sizeOf(Wrapper(1, "a"), Wrapper(2, "b"))
res24: (Long, Long) = (95,14)
scala> case class W(a: Int, b: String)
defined class W
scala> sizeOf(W(1, "a"), W(2, "b"))
res25: (Long, Long) = (89,14)
scala> case class Wrapper(first: Int, second: String)
defined class Wrapper
scala> sizeOf(Wrapper(1, "a"), Wrapper(2, "b"))
res26: (Long, Long) = (104,14)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.