Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NickNaso/6f01d4e62451313082050b38f86fcddc to your computer and use it in GitHub Desktop.
Save NickNaso/6f01d4e62451313082050b38f86fcddc to your computer and use it in GitHub Desktop.
Reusing Errors vs. creating new Error with stack attached
'use strict';
var ITER = 5E6
var ownStack = ~process.argv.indexOf('--stack')
var err = new Error('Some error that is reused');
function runWithoutstack() {
return err;
}
function runWithstack() {
return new Error('Some error that is not reused');
}
var start = process.hrtime()
, res
, fn = ownStack ? runWithstack : runWithoutstack
console.log('Running %s times. %s a new Error and thus %s a stack each time'
, ITER.toExponential()
, ownStack ? 'Creating' : 'Not creating'
, ownStack ? 'attaching' : 'not attaching')
for (var i = 0; i < ITER; i++) {
res = fn();
// just forcing v8 to not compile out our code
if (res.code === 1) console.log('ooops');
}
var diff = process.hrtime(start);
var diffNano = diff[0] * 1E9 + diff[1];
var perRunNano = diffNano / ITER;
console.log('Total time: %dms, Per run: %dns', diffNano / 1E6, perRunNano);

It is not usually recommended to reuse errors since the stack trace is attached whenever the error is instantiated.

However in some cases the overhead of doing that may affect performance, especially if the error is an exception that is known to occur frequently and is handled.

Only in these cases it may be advantagous to reuse the created Error. In all other cases getting a full stacktrace created at the time the exception occurs is to be preferred as it gives much better information needed to debug the problem.

Run

➝  node errors.js
Running 5e+6 times. Not creating a new Error and thus not attaching a stack each time
Total time: 57.412795ms, Per run: 11.482559ns

~/dev/js/benchmarks
➝  node errors.js  --stack
Running 5e+6 times. Creating a new Error and thus attaching a stack each time
Total time: 23250.284293ms, Per run: 4650.0568586ns

It follows that reusing errors results in a 450x speedup for creating errors in a tight loop. We need to keep in mind however that we are talking nanoseconds here, to put in perspective, creating one error with stacktrace takes 0.0046500568586ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment