How does V8 store integers in memory?
For example the integer 5?
I know it stores it the heap, but how exactly does it store it? Things like metadata and the actual value itself. Is there a constant added to the int before storing it?
How does V8 store integers in memory?
For example the integer 5?
I know it stores it the heap, but how exactly does it store it? Things like metadata and the actual value itself. Is there a constant added to the int before storing it?
V8 uses a pointer tagging scheme to distinguish small integers and heap object pointers. 5 would be stored as a Smi
type, which is not heap allocated in V8.
You can check out the source code for the Smi class to learn more.
On 32-bit platforms, Smis are a 31 bit signed int with a 0 set for the bottom bit. On 64-bit platforms, Smis are a 32 bit signed int, 31 bits of 0 padding and a 0 for the bottom bit. Pointers to heap objects have a 1 set for the bottom bit so that V8 can tell the difference between pointers and Smis without extra metadata.
In Javascript, all numbers are stored as 64bit floating point values. C and C++ call this type double
. There is no distinct "integer" type.
To some degree, you can use integer values naivly and get the result you expect, without having to fear rounding errors. These integers are so called "safe" integers.
All integers in the range [-(2^53 - 1), +(2^53 - 1)] are "safe" integers, as described here. This means that if you add, subtract or multiply integers in that range, and the result is within that range too, then the calculation is without rounding errors.
Of course, all values in Javascript/V8 are somehow "boxed", because a variable doesn't have a type (except small integers which use tagged pointers). If you have a variable x
that is 5.25
, it has to know that it is a "number" and that that number is 5.25. So it will take more than 8 bytes of space. You will have to look up the source code of v8 to find out more.