gpt4 book ai didi

javascript - "creation phase"怎么知道设置多少内存空间呢?

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:29 26 4
gpt4 key购买 nike

JavaScript: Understanding the Weird Parts讲师解释说,变量的内存是在所谓的创建阶段设置的(并且 undefined 已分配);然后执行阶段发生。但是,当我们不知道变量稍后将指向什么值时,为什么这很有用呢?

显然变量可以指向许多不同的东西——例如一个短字符串一直到一个深层嵌套的对象结构——我假设它们在所需的内存量上可能会有很大差异。

如果逐行执行——包括变量赋值——只发生在后面的执行阶段,初始创建阶段怎么知道如何设置内存?或者,是否只为每个变量名称/值对中的名称预留内存,而对值的内存以不同方式管理?

最佳答案

导师指的是Google Chrome's V8 engine (正如他在视频中使用它所证明的那样)。

V8 引擎使用多种优化方法来促进内存管理。首先,它将编译 JavaScript 代码,并在编译期间确定需要创建多少变量(隐藏类,稍后更多)。这些将决定最初分配的内存量。

V8 compiles JavaScript source code directly into machine code when it is first executed. There are no intermediate byte codes, no interpreter. Property access is handled by inline cache code that may be patched with other machine instructions as V8 executes. 1

第一组是通过浏览 JavaScript 代码以确定有多少不同的对象“形状”而创建的。任何没有原型(prototype)的东西都被认为是“过渡对象形状”

The main way objects are encoded is by separating the hidden class (description) from the object (content). When new objects are instantiated, they are created using the same initial hidden class as previous objects from the same constructor. As properties are added, objects transition from hidden class to hidden class, typically following previous transitions in the so-called “transition tree”. 2

相反,如果对象确实有原型(prototype),那么它将单独跟踪其特定形状。

Prototypes have 2 main phases: setup and use. Prototypes in the setup phase are encoded as dictionary objects. Any direct access to the prototype, or access through a prototype chain, will transition it to use state, making sure that all such accesses from now on are fast. 2

编译器基本上会将所有可能的变量读取为这两种可能的形状之一,然后分配必要的内存量以方便实例化这些形状。

一旦设置了第一组形状,V8 就会利用他们所谓的“快速属性访问”来构建在构建期间设置的第一组变量(隐藏类)。

To reduce the time required to access JavaScript properties V8 dynamically creates hidden classes behind the scenes 3

There are two advantages to using hidden classes: property access does not require a dictionary lookup, and they enable V8 to use the classic class-based optimization, inline caching 3

因此,在编译期间并非所有内存使用都是已知的,只知道为核心隐藏类集分配了多少内存。这种分配会随着代码的执行而增加,例如分配、内联缓存未命中和转换为字典模式(当太多属性分配给一个对象时会发生这种情况,以及其他几个细微的因素)。


1。动态机器代码生成,https://github.com/v8/v8/wiki/Design%20Elements#dynamic-machine-code-generation
<子>2。在 V8 中设置原型(prototype),https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2
<子>3。快速访问属性,https://github.com/v8/v8/wiki/Design%20Elements#fast-property-access

关于javascript - "creation phase"怎么知道设置多少内存空间呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43878471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com