In V8, how are primitive types such as null, undef

2020-04-19 08:36发布

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

In the book Speaking Javascript, it refers to a type tag being used to indicate the type of a value stored in memory. e.g. The type tag for Object type was 000. What is a type tag?

How would I find the type tag of a value type such as a boolean or string?

1条回答
贪生不怕死
2楼-- · 2020-04-19 09:10

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.

查看更多
登录 后发表回答