2

Does JavaScript optimize the size of variables stored in memory? For instance, will a variable that has a boolean value take up less space than one that has an integer value?

Basically, will the following array:

var array = new Array(8192);
for (var i = 0; i < array.length; i++)
  array[i] = true;

be any smaller in the computer's memory than:

var array = new Array(8192);
far (var i = 0; i < array.length; i++)
  array[i] = 9;
Tanaki
  • 2,575
  • 6
  • 30
  • 41

2 Answers2

1

Short answer: Yes.

Boolean's generally (and it will depend on the user agent and implementation) will take up 4 bytes, while integer's will take up 8.

Check out this other StackOverflow question to see how some others managed to measure memory footprints in JS: JavaScript object size

Edit: Section 8.5 of the ECMAScript Spec states the following:

The Number type has exactly 18437736874454810627 values, representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic

... so all numbers should, regardless of implementation, be 8 bytes.

Community
  • 1
  • 1
Cecchi
  • 1,525
  • 9
  • 9
  • @RobW, I can't remember where I came across this originally... it was lying in the back of my brain somewhere but I've added a reference that seems to agree with the back of my brain. – Cecchi Jul 10 '12 at 20:41
  • [This answer](http://stackoverflow.com/a/1248473/1048572) should lead you in the right direction – Bergi Jul 10 '12 at 20:46
0

Well, js has only one number type, which is a 64-bit float. Each character in a string is 16 bits ( src: douglas crockford's , javascript the good parts ). Handling of bools is probably thus interpreter implementation specific. if I remember correctly though, the V8 engine surely handles the 'Boolean' object as a 'c bool'.

vishakvkt
  • 864
  • 6
  • 7
  • 1
    What's a C bool? C doesn't have a boolean type. Also, V8 is written in C++. – davin Jul 10 '12 at 22:55
  • yeah that was a typo. I meant cpp bool. Good catch. But in terms of memory, they are absolutely the same, wherein when I say 'c bool', i mean its a char which is 8 bits. – vishakvkt Jul 11 '12 at 00:57