Does null occupy memory in javascript?

后端 未结 4 1015
孤城傲影
孤城傲影 2020-12-09 03:30

I\'ve got the following situation:

var large = [a,b,c,d,e,f,g,h,i];
var small = [a2, b2, c2, null, null, null, null, null, null, i2];

where

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 03:48

    Null will consume the memory only for the size of a word 'NULL' (in terms of interpreter), but the lookup will slow down because of the array overwhelmed with objects which will not go to the lookup result, and JS does not have a way to optimize this. You should better use the array of objects, and each object should keep a value and the index.

    Usage of undefined is tricky as well. In terms of interpretation and script size, this will increase a memory, but this is not a part of specs to advise whether undefined should consume memory and how much, so it is up to a browser, his facilities to garbage collect, consume memory heap etc. The best way to go is to try, probably. Run a relatively large array of both NULLs and undefined's within Chrome, take a heap snapshot and compare.

提交回复
热议问题