Serialization pads to 4K boundary?

  • Thread starter Thread starter David
  • Start date Start date
D

David

In a .NET 3.0 app I'm serializing objects to a byte array:

Dim ms As New MemoryStream
Dim bf As New BinaryFormatter

bf.Serialize(ms, obj) ' serialize passed object to
a memorystream

Dim ba() As Byte = ms.GetBuffer ' get byte array from
memorystream

But I've noticed that the byte array returned by GetBuffer always seems to
be a multiple of 4096 bytes. And upon inspection, it appears that it is being
padded with binary zeros.

Does anyone know if the padding is being added by the Serialize method, or
is it a result of using a MemoryStream, or by GetBuffer?

How can I prevent this padding? And is it possible to directly serialize
an object to a byte array, bypassing the use of a MemoryStream?

It's very important in this app to minimize the size of each of these byte
arrays, as I'm serializing tens-of-thousands of objects for transport between
systems, and the "pad" can add-up.

TIA
 
GetBuffer() returns exactly that - the internal buffer used by the memory
stream; useful if you want to avoid a block-copy (as long as you check the
Length correctly).

If you want *just* the content, try ToArray() instead.

Marc
 
Back
Top