Bincode: Serialized size difference between b".." and "..".as_bytes()

Hi Guys,

using the Bincode library, why is there a size difference when I do the following?

let size = bincode::serialized_size(b"hellobello").unwrap();
// here the size is 10

let size = bincode::serialized_size("hellobello".as_bytes()).unwrap();
// here the size is 18

So with the following bytes - as valid ASCII characters - should take 1 byte per character, that means 10 char * 1 byte => 10 bytes.

But when I use a &[u8] or a "..".as_bytes(), the size is almost double. Why?

Thank you in advance.

b"hellobello" is of type [u8; 10]. You can deserialize it to [u8; 10], and the serialized form only needs to store 10 bytes.

"hellobello".as_bytes() is of type &[u8]. To deserialize it, the serialization has to also contain the length of the slice, because a [u8] can be any length.

(I don't know anything about bincode specifically, but) I assume those extra 8 bytes are just the length of the slice.

5 Likes

Yes, I checked the serialized bytes, and you are right.

b"hellobello" = [104, 101, 108, 108, 111, 98, 101, 108, 108, 111]
"hellobello".as_bytes() = [10, 0, 0, 0, 0, 0, 0, 0, 104, 101, 108, 108, 111, 98, 101, 108, 108, 111]