Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON stringification turns 47 byte json string to 340mb?

var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};

var temp = [];
for (var i = 0; i < keys.length; i++) {
    temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);

When I run that script in Chrome I get, after a good amount of time, an output of 340666156.

My question is... how?

The commented out alert outputs 47. Seems to me that the second alert should yield the same result? That temp should pretty much be an exact copy of val?

The jsfiddle of it:

http://jsfiddle.net/vMMd2/

Oh - and if you want to crash your browser window (well it crashed my Google Chrome window) just add the following to the end:

temp.forEach(function(entry) {
    alert(temp);
});

Any ideas?

like image 960
neubert Avatar asked Dec 01 '22 20:12

neubert


1 Answers

var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};

var temp = {}; //  <--- !!!
for (var i = 0; i < keys.length; i++) {
    temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);

http://jsfiddle.net/zerkms/vMMd2/2/

You're creating a sparse array, and presumably V8 initializes all the gaps with some garbage null undefined values (thanks to nnnnnn for checking that). It takes some time

like image 79
zerkms Avatar answered Dec 10 '22 13:12

zerkms