Arvind
Arvind

Reputation: 1247

Find JSON object size without parsing it to string

I know I can get the size of a JSON object in bytes by using JSON.parse(data).length.
//UTF-8 etc can be ignored for now but parsing takes time for huge data which I don't want.

Is there any way to get its size in MB without transforming it to a string?

Upvotes: 3

Views: 5774

Answers (3)

ccordon
ccordon

Reputation: 1102

There is no native way to calculate the size of an object in Javascript but there is a node module that gives you the size of an object in bytes. object-sizeof

This would be an example of what you need:  

var sizeof = require('object-sizeof');

// 2B per character, 6 chars total => 12B

console.log(`${sizeof({abc: 'def'})/1024} MB`);

Upvotes: 1

Robb216
Robb216

Reputation: 552

For security reasons, Javascript is not allowed to access or mutate information about the device, therefore, determining exactly how many bytes an object occupies should be impossible.

With that being said, the following Javascript command DOES exist (within chrome only):

window.performance.memory

This returns an object with the amount of bytes the window can use at maximum, the amount of bytes used including free space, and the amount of bytes actually used. You could, theoretically, use that to determine the amount of bytes used before an object was created and after, and calculate the difference. The memory-stats project for instance utilizes that command.

However, the values in this object never change except if chrome was launched with the "--enable-precise-memory-info" flag. You therefore cannot use this command in a (production) application (the MDN docs indicate the same). You can only approach the amount of memory an object occupies by counting all the strings and numbers and multiplying that by how much bytes a string usually occupies (which is what the object-sizeof library does).

If you are just interested in the size of the object and do not wish to use that information in a production app, you can simply do so by making a timeline recording in the Chrome Devtools.

Upvotes: 1

Yaroslav Gaponov
Yaroslav Gaponov

Reputation: 2099

We have next options:

  • Recurring calculation like object-sizeof library
  • object to string/buffer:
    1. JSON.stringify({a:1}).length
    2. v8.serialize({a:1}).length

Upvotes: 1

Related Questions