3

According to this question: (Socket.io: How to limit the size of emitted data from client to the websocket server), you can roughly calculate the size of packets by turning the data into a JSON string and finding the length of it.

Wouldn't that mean that, for instance, the number 12345678 takes just as many bytes as the string "12345678", even though one is a string and one is a number?

Also, does that mean that rounding numbers would decrease size? So, instead of 3.49362627, you could send 3.5.

Would decreasing the length of property tags improve size too? Instead of: {width: 4}, you could {w: 4}.

Thank you help with understanding the size of packets sent by socket.io. Any other general optimization tips are appreciated.

Weastie
  • 157
  • 10

1 Answers1

3

Socket.io serialization/deserialization is performed by JSON.stringify()/JSON.parse(). Everything becomes strings in the process. So indeed, you'd better format your numbers into smaller strings if you want to minimize packet size (e.g. with toFixed). Note that in JSON format, double-quotes " are added around strings, which makes it 2 bytes longer.

Another consequence: object's functions are lost in the process of serialization.

Optimization tips:

  1. It is generally more efficient to recompute data (e.g. unzip) rather than moving data around (network, disk, ...). So your approach is valid.

  2. Always measure performance before optimizing. You will often be surprised that an "optimization" just made your performance worse.

Note also that JSON.stringify calls your object's toJSON function.

RaphaMex
  • 2,781
  • 1
  • 14
  • 30
  • Building off of this, I found a few silly ways to send less bytes! 1) Use 1 and 0 instead of true and false. 2) On the server side, don't send any objects. Just send arrays, and have the client parse that into an object using the order of elements. – Weastie Apr 30 '18 at 22:42