Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json boolean vs integer - which takes up less space?

Tags:

json

When sending a value in JSON otw, is it better to use a boolean or an integer to use up less space?

e.g:

{
  foo: false
}

Or:

{
  foo: 0
}

Would using a number use less space, considering its just a number, compared to 4 or 5 characters for a boolean value? (true/false)

Also is there a speed difference between the two approaches if you convert them from JSON to object format?

like image 908
pizzae Avatar asked Dec 18 '17 14:12

pizzae


People also ask

Can JSON store Boolean?

JSON supports mainly 6 data types: number. boolean. null.

Is JSON Boolean case sensitive?

JSON is case sensitive to both field names and data. So is N1QL.

Can you have integers in JSON?

Numbers in JSON must be an integer or a floating point.

Does JSON support long?

As a practical matter, Javascript integers are limited to about 2^53 (there are no integers; just IEEE floats). But the JSON spec is quite clear that JSON numbers are unlimited size.


1 Answers

Firstly, this is micro-optimisation, and very unlikely to be important. If you are transporting thousands or millions of such values, it might become significant; but in that case, you probably want something much more efficient than JSON anyway (a plain CSV would be better in many cases, but ideally you'd use some packed binary format).

Secondly, JSON is a way of representing data in a string; so storing or sending JSON means you are storing or sending strings. Measuring the size of the data is therefore trivial: how long is the string? The string 0 has one character; the string false has five characters.

Thirdly, if you're optimising for space, you'd remove all insignificant whitespace, so your examples should be {"foo":false} (13 characters) and {"foo":0} (9 characters). Note that you can't, as you have in your example, skip the quote marks around foo - that is not valid JSON.

Fourthly, how much memory or other resources the structure will take up when you convert it from JSON into an object depends on what language you're using, what implementation of that language, and any number of other factors, so is completely unanswerable (and, again, a micro-optimisation that is very unlikely to be important).

like image 192
IMSoP Avatar answered Oct 17 '22 05:10

IMSoP