javascript - Error 对象的堆栈是什么时候产生的?

标签 javascript v8

每次我实例化一个 Error 对象时,都有一个 .stack 字段。假设构建堆栈跟踪是一项代价高昂的操作,我的自然 react 是保留它们用于特殊情况。

不过我记得读过,在 v8 中,堆栈跟踪仅在读取 .stack 字段时计算。

如果我从不读取堆栈,我可以假设 new Error(...)new Object(...) 一样昂贵吗?

这是 JS 引擎的特性还是标准行为?

最佳答案

Error.prototype.stack是非标准功能,因此其行为取决于实现。

对于基于 V8 的平台,wiki在 GitHub 上说:

The stack trace is collected when the error is created and is the same regardless of where or how many times the error is thrown.

还有 document Node.js 也说了同样的话:

Error objects capture a "stack trace" detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.

因此当 Error 对象被创建时它已经被收集

但是,直到第一次访问 stack 属性时,它才格式化,如同一维基页面上的段落所述:

For efficiency stack traces are not formatted when they are captured but on demand, the first time the stack property is accessed.

关于javascript - Error 对象的堆栈是什么时候产生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45541554/

相关文章:

c++ - mac 上的 node-gyp 构建错误 "calling a protected constructor of class ' v8::HandleScope'"

V8 中 Javascript 的奇怪性能

javascript - RegExp.Test 总是返回 false

javascript - JavaScript 中的 timeout 和 interval 是否使用单调时间?

javascript - 如何限制多个通配符搜索?

javascript - 创建元素并独立滚动它们

javascript - 如何将代码从多个 if 语句更改为 Switch Case 语句

javascript - Android 使用没有 WebView 的 V8

javascript - 是否可以使用正则表达式匹配字符串的一半或使用匹配组的一半?

javascript - console.log 避免最大调用堆栈