JSON string turning json 47-byte string into 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 this script in Chrome, I get 340666156 output after a good amount of time.

My question is ... how?

The recorded warning outputs 47. It seems to me that the second warning should give the same result? This pace should pretty much be an exact copy of val?

Jsfiddle value:

http://jsfiddle.net/vMMd2/

Oh - and if you want to minimize your browser window (well, that broke my Google Chrome window), just add the following to the end:

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

Any ideas?

+4
source share
2 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 create a sparse array and presumably V8 initializes all spaces with some garbage null undefined values ​​(thanks to nnnnnn for checking this). Takes some time

+11
source

@zerkms, is correct. But I also wanted to indicate why this is happening.

 > var temp = []; > temp[10] = 'test'; > temp [ , , , , , , , , , , 'test' ] 

As you can see, it creates 9 undefined values. I ran above with nodejs, so null values ​​are not displayed.

If I made JSON.stringfy (), you will see:

 > JSON.stringify(temp) '[null,null,null,null,null,null,null,null,null,null,"test"]' 
+7
source

All Articles