43

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 , 8 byte of memory . now data Type like Number , string , boolean , null , undefind and Objects , Arrays in javascript how many use of memory and what is ranges that accepted ? Accept my apologize because of my low English level!!!

Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159
  • 1
    Unlike C, in JS there's no specific memory layout mandated for a given type of value, it depends on the JS engine and even on how the value was created (for example, `"literal string"` vs concatenating other strings). The answers here focus on the payload size, which may be shared between different objects, and don't include the overhead for the object itself (see https://stackoverflow.com/a/45808835/1026 or https://stackoverflow.com/a/18975098/1026 for examples). – Nickolay May 27 '18 at 13:44

3 Answers3

30

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.

Community
  • 1
  • 1
Rani Kheir
  • 1,049
  • 12
  • 15
  • 2
    getByteCount detects the number of % in an url-encoded version of a string, which is the number of bytes that an UTF-8 encoding would need. This is unrelated to the representation in memory. – Rolf Oct 10 '18 at 14:55
  • 6
    4 bytes for a boolean :D?? – Adam Aug 16 '19 at 06:30
  • 2
    but surely an empty string doesnt only take up 0 bytes? – feihcsim Jul 26 '20 at 05:33
19

As of today, MDN Data Structures page gives some more info about it:

Number

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value

So that should amount to 8 bytes.

String

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values.

So that should amount to 2 bytes per character.

Boolean

Boolean represents a logical entity and can have two values: true, and false.

Nothing more about that.

aleclarson
  • 18,087
  • 14
  • 64
  • 91
superjos
  • 12,189
  • 6
  • 89
  • 134
  • 1
    Question: isn't boolean's definition also telling you the answer? Since it's either on or off and bits are either 1/0, then shouldn't a boolean value be 1 bit? – Kitanga Nday Jun 04 '17 at 20:51
  • 17
    Well, no, the fact that 1 bit is enough to store a boolean, does not imply that a boolean will be stored in 1 bit, due to reasons like memory management and addressing techniques. At least when I was studying computer architectures :), a byte was the smallest amount of addressable memory. See e.g. [this SO question](https://stackoverflow.com/questions/2064550/c-why-bool-is-8-bits-long) for an answer – superjos Jun 05 '17 at 16:38
  • 3
    @KitangaNday actually a boolean is stored with **4 bytes**, see accepted answer – Adam Aug 16 '19 at 06:32
  • @Adam yes, I know . I read the accepted answer a long time ago. – Kitanga Nday Aug 18 '19 at 16:22
  • @superjos I found [this](https://qr.ae/TWrUvd) on the interwebs, and I think it might answer why Boolean is actually 4 bytes. – Kitanga Nday Aug 18 '19 at 16:25
  • @KitangaNday not sure how that relates to JS though, it is about C++, and specifically about VS 4.2 "implementation", so to say. – superjos Aug 22 '19 at 12:12
  • @superjos All the [Well known Javascript engines](https://en.wikipedia.org/wiki/JavaScript_engine#Notable_engines) are implemented using C++. So you could assume that the types could be similar. Also, I don't think the Boolean type has changed much since then. And that VS reference was a bit weird to me. But it must mean that when VS creates your executable then it sets the boolean to 4 bytes. Anyways, just thought it might interest you. – Kitanga Nday Aug 22 '19 at 21:36
  • And about Symbol ? – Ayfri Jul 24 '20 at 20:42
2

The memory representation of a value, in other words its size, is an implementation detail unless it is specified otherwise, and can be different depending on the underlying code of the runtime environment. Runtime is the application that runs the JavaScript code i.e Nodejs, Firefox Browser or Chrome Browser.

Let's say you writing your own runtime and you want to represent a boolean value. A boolean value requires at least one bit, so you can store it in the memory as a single bit.

This is true:

This is false:

But there is nothing stopping you to use 8 bits or one byte memory space. Here most significant bit holds the value, rest will be padded with 0:

□□□□□□□■

Or 64 bits:

□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□■

Same thing applies to a string value. You can represent it using 8 bits or 64bit or even more. However language promises to operate on any Unicode value, but 8 bits may not be large enough to represent all Unicode values. That is where you find some addressing and adjustments in the specification. The string in JavaScript is treated as a sequence of UTF-16 code units and some character takes up 16 bits memory space and others 32 bits.

Code unit is a term borrowed from the Unicode specification. You may ask why not a character but a code unit, because character is one way to represent a specific textual data and there are other ways too. For example both é, \u00E9 and \u{E9} creates letter e with acute. In your JavaScript string, you can prefer either of those.

Math is tricky because at CPU level all calculations are done in binary, and binary does not translate to decimal without issues. Try running 0.1 + 0.1 == 0.3. So we need tighter control for accuracy. That is why specification is very specific on the number representation: the double-precision 64-bit binary format IEEE 754.

To sum up, when writing a JavaScript runtime, how you store a value in the memory is up to you, unless it is clearly specified in the spec. That is why some data types have lengthy discussions on how they should be represented and stored in the memory.

Runtime environments are generally written in lower level languages such as C, C++ or Rust and memory management is delegated to what those languages use.

If you are JavaScript programmer you don't need to concern yourself how memory is allocated and freed because runtime handles that part for us. The only possible issue you might have is memory leaks through circular references: Object A has a reference to object B, and object B has a reference to object A. There are tools in the developer console to detect such issues.

snnsnn
  • 10,486
  • 4
  • 39
  • 44