关于Socket.io/Node.js发送JSON数据大小的技术问询
Hey there! Since you're sending these JSON payloads 10 times a second via Socket.io, every tiny byte adds up—so great call asking these questions. Let's break each one down clearly:
1. Do tabs/spaces in object literals affect sent data size?
Short answer: No, they don't.
The spaces/tabs you use in your JavaScript object literal (like the difference between your two code snippets) are just for readability in your code. When Socket.io serializes your object to JSON for transmission, it uses JSON.stringify() under the hood with default settings—which produces a compact, whitespace-free string.
For example, both of these:
return { id:self.id, username:self.username, score:self.score, level:self.level };
and
return {id:self.id,username:self.username,score:self.score,level:self.level};
will get serialized to the exact same JSON string, something like:
{"id":"user123","username":"jane","score":95,"level":3}
The extra spaces in your code don't make it into the final transmitted data, so they have zero impact on payload size.
2. Size difference between 0/1 vs true/false in JSON?
Absolutely—there's a clear difference here. Let's look at the serialized output:
truebecomes"true"(4 characters)falsebecomes"false"(5 characters)0becomes"0"(1 character)1becomes"1"(1 character)
For a key-value pair like "isOnline": true, that's 14 characters (including quotes and colon). Swap it to "isOnline": 1, and it's only 12 characters. Multiply that by 10 sends per second, and over time those extra bytes add up. If you're using boolean flags, replacing them with 0/1 will definitely reduce your payload size.
3. Size difference between string "11" vs number 11 in JSON?
Yes, the number version is smaller. Here's why:
- The string
"11"gets serialized as"11"(with quotes), so a pair like"score": "11"is 9 characters total. - The number
11gets serialized as11(no quotes), so"score": 11is only 7 characters.
That's 2 fewer bytes per occurrence. Again, with 10 sends per second, this adds up over time. If your values are numeric (like scores, levels), always use the number type instead of wrapping them in quotes as strings to save space.
内容的提问来源于stack exchange,提问作者leonylyner

