Memory usage of JavaScript objects with numeric keys

∥☆過路亽.° 提交于 2021-01-28 14:09:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!