Avoid try/catch in performance-critical functions

suggest change

Older JavaScript engines (Chrome before Ignition and TurboFan, and Node.js versions from that era) did not optimize functions that contained a try/catch block. Current V8 does not have that limitation.

If you need to handle exceptions in performance-critical code, it can be faster in some cases to keep the try/catch in a separate function. For example, this function will not be optimized by some implementations:

function myPerformanceCriticalFunction() {
    try {
        // do complex calculations here
    } catch (e) {
        console.log(e);
    }
}

However, you can refactor to move the slow code into a separate function (that can be optimized) and call it from inside the try block.

// This function can be optimized
function doCalculations() {
    // do complex calculations here
}

// Still not always optimized, but it's not doing much so the performance doesn't matter
function myPerformanceCriticalFunction() {
    try {
        doCalculations();
    } catch (e) {
        console.log(e);
    }
}

A historical jsPerf comparison is at https://jsperf.com/try-catch-deoptimization (the site may no longer run it). In current browsers there is usually little or no difference. In old Chrome, Firefox, and Internet Explorer, calling a helper from inside try/catch was often faster.

Note that optimizations like this should be made carefully and with actual evidence based on profiling your code. As JavaScript engines get better, it could end up hurting performance instead of helping, or making no difference at all (but complicating the code for no reason). Whether it helps, hurts, or makes no difference can depend on a lot of factors, so always measure the effects on your code. That’s true of all optimizations, but especially micro-optimizations like this that depend on low-level details of the compiler/runtime.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents