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.
➝ 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
.