Serialized size


Is it possible to discover how large something will be when it’s serialized?

I have a data type:
NamedTuple{(:x, :y), Tuple{UInt64, UInt64}}

sizeof tells me this is 16 bytes, and the serialize documentation says that it will add an 8-byte header - which gives 24 bytes. However, experiments show that the serialized form is actually 34 bytes. So sizeof clearly isn’t giving me what I need. Is there something I can use programmatically?


Perhaps not the most efficient, but you can create your own IO type like this:

mutable struct ByteCounterIO <: IO
    ByteCounterIO() = new(0)

Base.write(s::ByteCounterIO, x::UInt8) = s.count += 1

io = ByteCounterIO()
t = (x = 34, y = 18)

using Serialization
serialize(io, t)



Are you constructing a Serializer object and writing the header once with Serialization.writeheader as suggested in the docs? Unless you do this, Serializer.serialize will write a header each time you serialize something if you use it on an <: IO stream.