问题
Looks like the memory required to hold a memory structure with Javascript Objects doesn't only rely on the number of stored objects but also the used keys.
Let's write, for example, this simple code in fiddlejs (link below):
for (var i=0; i<500; i++) {
o[i]={};
for (var j=0; j<500; j++) {
o[i][j]={};
o[i][j]['abc'] = {};
}
}
https://jsfiddle.net/9Lespw7g/
Then run the script and open the Chrome memory tab (or take a memory snapshot with Firefox). At this point the profiler should show something like 16MB of allocated memory.
Now simply replace the 'abc' key with '900' in the previous code. (link below)
for (var i=0; i<500; i++) {
o[i]={};
for (var j=0; j<500; j++) {
o[i][j]={};
o[i][j]['900'] = {};
}
}
https://jsfiddle.net/cfm0n7xq/
Now the memory profiler shows that more that 1400MB is allocated which make a big difference.
Since this behavior is the same in both Chrome & Firefox, I would like to understand the underlying concepts to avoid unpleasant surprises in the futur when I'm using Javascript Objects
Thank you.
来源:https://stackoverflow.com/questions/65270531/memory-usage-of-javascript-objects-with-numeric-keys