In V8, how are primitive types such as null, undefined, and boolean stored in memory?

后端 未结 1 996
时光说笑
时光说笑 2021-01-21 14:28

Is a boolean stored as a 32-bit integer in memory? How about a null value?

In the book Speaking Javascript, it refers to a type tag

相关标签:
1条回答
  • 2021-01-21 14:57

    From Andy Wingo's blog post on the topic:

    Initially, all JavaScript implementations used tagged pointers to represent JS values. This is a old trick that comes from the observation that allocated memory takes up at least 4 or 8 bytes, and are aligned in such a way that the least significant bit or three will be zero.

    So the type tags allow for all values to be stored uniformly. All values occupy one machine word (32/64 bit) and depending on the tag (which is the least significant bit or bits) they are interpreted either as a pointer to an object or as some integer/boolean/etc depending on the tag.

    is boolean stored as a 32-byte integer in js memory?

    A boolean also occupies one word. For a more specific answer I'd need to go though the v8 source. But if I remember correctly, true and false are represented as root pointers.

    how to get the type tag of a value type(boolean,undefined,string, number);

    No way to do it from JavaScript. It's internal implementation details.

    0 讨论(0)
提交回复
热议问题