Every time I instantiate an Error object there is a .stack
field. Assuming that building a stacktrace is a costly operation, my natural reaction is to reserve their use for exceptional cases.
However I remember reading that in v8 the stacktrace is only calculated upon read of the .stack
field.
Can I assume that new Error(...)
is just as expensive as new Object(...)
if I never read the stack ?
Is this a feature of the JS engine or a standard behavior?
Error.prototype.stack
is a non-standard feature, so its behavior depends on the implementation.
In the case of platforms based on V8, the wiki on the GitHub says:
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.
And the document of Node.js also says the same thing:
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.
So it is already collected when the Error
object is created.
However, it is not formatted until the first time the stack
property is accessed, as the paragraph on the same wiki page states:
For efficiency stack traces are not formatted when they are captured but on demand, the first time the stack property is accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With