Search code examples
jsonserializationcbor

Question about JSON vs CBOR serialization


I have a theorical doubt about how serialization works, and especially about the difference between serialization schemes like JSON and binary serialization schemes like CBOR.

My question is: if a JSON serializer converts an object into a JSON string, then, to store or transmit the resulting JSON string, do you have to also convert the JSON string into its bytes representation? Is this why binary schemes might be faster, since they produce a binary output already?


Solution

  • In memory, a string is anyway represented as a sequence of bytes (actually, everything is just a sequence of bytes in memory), so this should not matter.

    What matters is the conversion from the in-memory representation of a Javascript variable into the in-memory representation of its string equivalent. An extremely simply example is a numeric variable with value -1. This can be internally represented by one byte:

    > Buffer.of(-1)
    <Buffer ff>
    

    but its JSON serialization "-1" takes two bytes:

    > Buffer.from(JSON.stringify(-1))
    <Buffer 2d 31>
    

    And the JSON serialization also takes time.

    This should give an idea why a binary scheme that sticks closer to the internal representation can be output (and input) faster.