newguy newguy - 1 year ago 69
Javascript Question

What is the difference between sending JSON.stringify objects and plain objects in javascript sockets?

I am building a javascript socket application which uses
and I am new to network programming. I don't know what is the best way to pass data in the network. I understand that passing binary data is the most efficient way but it is more complicated. So I want to start with plain object for now.

I have built a chat application before in which I just used
socket.emit('message', obj)
and it works perfectly fine. But I have seen some examples passing the data using
socket.emit('message', JSON.stringify(obj))
. I am not sure what the benefit is here. Does it make the data passing on the network smaller size? Is it more efficient than plain object?

Answer Source

By default, will call stringify for you so it's pointless to do it manually.

Most likely, simple socket.emit('message', obj) does what you want. Even if you want to emit binary, that's how it done. It seems it "just works", there is not much documentation about it. Basically, you have to emit something that passes hasBin-check ie. it has to be Buffer, ArrayBuffer, Blob or File.

There is no Buffer.fromObject-method in Node.js API, for a reason. If you want to send your Object as binary, you have to design how to represent it as binary data. Whether or not, it's good idea, depends on what kind of data you are dealing with. If your data is mostly strings, then you can't shim it much. If you have a lot of integers, numbers, booleans etc, then using binary might be good idea, but it's quite bit of extra work to design efficient binary format.

Also, there is a format called BSON. It has browser implementations too, so technically it should be possible to serialize arbitrary Javascript Object to Buffer, send using and then deserialize it in browser. I haven't ever used it in browser environment: it sounds like interesting idea but it would need some performance testing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download