When is the stack of Error objects created?

Every time I create an Error object a box appears .stack

. Assuming building a stacktrace is an expensive operation, my natural reaction is to reserve them for exceptional cases.

However, I remember reading that in v8, the stacktrace is only calculated after the field is read .stack

.

Is it new Error(...)

as expensive as new Object(...)

if I never read the stack?

Is this a feature of the JS engine or standard behavior?

+3


source to share


1 answer


Error.prototype.stack

is a non-standard function, so its behavior is implementation dependent.

In the case of V8-based platforms, the wiki on GitHub says:

The stack trace is collected when an error occurs and is the same regardless of where and how many times the error occurs.

And document Node.js says the same thing too:



Error objects capture a "stack trace", detailing the point in the code in which the error was generated, and can provide text describing the error.

So it is already assembled when the object is created Error

.

However, it is not formatted until the property is accessed stack

, as in a paragraph on the same wiki page:

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

+3


source







All Articles