The try/catch block is a unique construct, both in how it works and what it is capable of. Fundamentally, it is able to isolate one or more statements to capture and suppress any runtime errors that may be encountered as a result of execution. It is such a powerful construct that in a perfect world you would want to wrap everything in a try/catch block to provide simple and effective error trapping. However, due to concerns in performance critical situations, employing it is often frowned upon in JavaScript. But what if I told you there was a means of emulating the try/catch block in JavaScript without the concern for performance? This article will be exploring just such a method.
Your new post is loading...
What makes this construct unique is in the manner in which the catch block augments the scope chain. Rather than creating a new execution context and pushing it to the top of the execution stack, the catch block will actually create a new variable object and place it ahead of the activation object in the scope chain of the current execution context. This creates what is known as a dynamic scope, similar to the effect of the with statement, which lends to its bad reputation as well. As a result, the error object passed to the catch block does not exist outside of it, even within the same scope. It is created at the start of the catch clause and destroyed at the end of it. This type of manipulation of the scope chain is the primary reason for the performance hit.
At this point you may be thinking that as long as an error is not raised than performance should not be affected. That is a fair assumption, but you’d be wrong. Some JavaScript engines, such as V8 (Chrome) do not optimize functions that make use of a try/catch block as the optimizing compiler will skip it when encountered. No matter what context you use a try/catch block in, there will always be an inherent performance hit, quite possibly a substantial one.
These limitations are well documented, for instance, look at the following test cases: http://jsperf.com/try-catch-block-performance-comparisonand http://jsperf.com/try-catch-block-loop-performance-comparison.
The former confirms that not only is there up to a 90% loss in performance when no error even occurs, but the performance is significantly worse when an error is raised and control enters the catch block. The latter test case proves that the loss is compounded in loops, where most performance intensive operations typically occur.