Memory Usage Of Different Data Types in javascript

后端 未结 2 1828
孤独总比滥情好
孤独总比滥情好 2020-12-15 04:23

A question that has happened to me is that different Data type in javascript how many use of memory . for Example in C++ data type like int , char , float uses order 2 , 1 ,

2条回答
  •  半阙折子戏
    2020-12-15 04:43

    Numbers are 8 bytes.

    Found that in this w3schools page.

    I searched around a bit more for other JavaScript primitive types, but it's surprisingly hard to find this information! I did find the following code though:

        ...
        if ( typeof value === 'boolean' ) {
            bytes += 4;
        }
        else if ( typeof value === 'string' ) {
            bytes += value.length * 2;
        }
        else if ( typeof value === 'number' ) {
            bytes += 8;
        }
        ...
    

    Seems to indicate that a String is 2 bytes per character, and a boolean is 4 bytes.

    Found that code here and here. The full code's actually used to get the rough size of an object.

    Although, upon further reading, I found this interesting code by konijn on this page: Count byte length of string.

    function getByteCount( s )
    {
      var count = 0, stringLength = s.length, i;
      s = String( s || "" );
      for( i = 0 ; i < stringLength ; i++ )
      {
        var partCount = encodeURI( s[i] ).split("%").length;
        count += partCount==1?1:partCount-1;
      }
      return count;
    }
    getByteCount("i♥js"); // 6 bytes
    getByteCount("abcd"); // 4 bytes
    

    So it seems that the string's size in memory depends on the characters themselves. Although I am still trying to figure out why he set the count to 1 if it's 1, otherwise he took count-1 (in the for loop).

    Will update post if I find anything else.

提交回复
热议问题