Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the stack of Error objects generated?

Tags:

javascript

v8

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?

like image 749
SystematicFrank Avatar asked Oct 20 '25 10:10

SystematicFrank


1 Answers

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.

like image 174
Microloft Avatar answered Oct 22 '25 00:10

Microloft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!