Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance hit of newing up Error object in modern Node.js

There are usecases where its necessary to new up an Error object for the purpose of retrieving a stack trace, such as for logging engines or inline debugging.

Is there a heavy performance hit in modern node.js when the Error object is first created or has the smart V8 developers figured out to unwind the stack on demand just when the developer calls <Error>.stack property.

From my probing of the tools, I think that the stack trace unwinding is not executed until <Error>.stack is accessed and it seems a common sense design approach.

Can anybody shed light on this or suggest ways to verify short of debugging the native V8 code?

like image 994
Timothy C. Quinn Avatar asked Feb 10 '16 03:02

Timothy C. Quinn


People also ask

How would you handle errors for async code in node js?

If we want to handle the error for asynchronous code in Node. js then we can do it in the following two manners. Handle error using callback: A callback function is to perform some operation after the function execution is completed. We can call our callback function after an asynchronous operation is completed.

How can I improve node js API performance?

Caching is one of the common ways of improving the Node Js performance. Caching can be done for both client-side and server-side web applications. However, server-side caching is the most preferred choice for Node Js performance optimization because it has JavaScript, CSS sheets, HTML pages, etc.


1 Answers

I built a benchmark test and posted it to my github repo. The results of my tests confirms that the V8 engine behind node.js captures stack information at the point of creation of any Error objects, including sub-classes of Error.

My test is rather elaborate but I wanted to ensure I bypassed any optimizations in V8 for unwinding the call stack. I implemented this by generating a random call stack on each test iteration. I also experimented with calling Error.stack and not calling Error.stack and the impact of this was negligible.

Its interesting to note that the performance hit for construction of the Error, unwinding a stack of just over 10 steps in length and pulling the stack trace as a string costed only about 87 microseconds. The cost for constructing a generic object as about 21 microseconds.

I also found a note on the V8 Github repository Stack Trace API page:

Note that the custom prepareStackTrace function is immediately called at the point when the error object is created (e.g. with new Error()).

like image 116
Timothy C. Quinn Avatar answered Oct 12 '22 17:10

Timothy C. Quinn