Error 对象的堆栈是什么时候产生的?
When is the stack of Error objects generated?
每次我实例化一个 Error 对象时,都会有一个 .stack
字段。假设构建堆栈跟踪是一项代价高昂的操作,我的自然反应是保留它们用于特殊情况。
不过我记得在 v8 中读过,堆栈跟踪仅在读取 .stack
字段时计算。
如果我从不阅读堆栈,我可以假设 new Error(...)
和 new Object(...)
一样昂贵吗?
这是 JS 引擎的特性还是标准行为?
Error.prototype.stack
是非标准功能,因此其行为取决于实现。
对于基于 V8 的平台,GitHub 上的 wiki 表示:
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.
和Node.js的document也说了同样的话:
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.
每次我实例化一个 Error 对象时,都会有一个 .stack
字段。假设构建堆栈跟踪是一项代价高昂的操作,我的自然反应是保留它们用于特殊情况。
不过我记得在 v8 中读过,堆栈跟踪仅在读取 .stack
字段时计算。
如果我从不阅读堆栈,我可以假设 new Error(...)
和 new Object(...)
一样昂贵吗?
这是 JS 引擎的特性还是标准行为?
Error.prototype.stack
是非标准功能,因此其行为取决于实现。
对于基于 V8 的平台,GitHub 上的 wiki 表示:
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.
和Node.js的document也说了同样的话:
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.