BSON : Introduction

BSON – Binary JSON gets my attentions lately when I was working on a messaging system implementation, where the main requirement was “optimal performance”.

bson

What is BSON

BSON is designed to be efficient in space, but in some cases is not much more efficient than JSON. In some cases BSON uses even more space than JSON. The reason for this is another of the BSON design goals: traversability. BSON adds some “extra” information to documents, like length of strings and subobjects. This makes traversal faster.

BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don’t need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.

(from : http://bsonspec.org/)

A Quick Hands on

BSON libraries are available for almost all popular languages, from C to Swift, in this hands on I thought to experiment with Python.

Install BSON via  pip install bson
Open Python shell
>>>import bson
>>>bson_foo = bson.dumps({"foo":"bar"})
>>>print(bson_foo)
Now you should be able to see some non-human-readable some data. Because BSON was not designed for human readability, as JSON.
To check the size of the bson_foo,
>>>import sys
>>>sys.getsizeof(bson_foo)
this gives, 51.
For the benchmarking, lets compare the same with JSON,
>>>import json
>>>json_foo = json.dumps({"foo":"bar"})
>>>print(json_foo)
>>>sys.getsizeof(json_foo)
this gives, 63.
So it seems, for simple JSON representations like this, BSON takes less amount of memory. Also, its optimal in traversing through the document.

Happy Coding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s