Is it \"slow\" to use several try-catch blocks when no exceptions are thrown in any of them? My question is the same as this one, but for JavaScript.
Suppose I have
The original question asked about the cost of try/catch when an error was not thrown. There is definitely an impact when protecting a block of code with try/catch, but the impact of try/catch will vanish quickly as the code being protected becomes even slightly complex.
Consider this test: http://jsperf.com/try-catch-performance-jls/2
A simple increment runs at 356,800,000 iterations per second The same increment within a try/catch is 93,500,000 iterations per second. That's on overhead of 75% due to try/catch. BUT, a trivial function call runs at 112,200,000 iterations per second. 2 trivial function calls run at 61,300,000 iterations per second.
An un-exercised try in this test takes slightly more time than one trivial function call. That's hardly a speed penalty that matters except in the inner-most loop of something really intense like an FFT.
The case you want to avoid is the case where an exception is actually thrown. That is immensely slower, as shown in the above link.
Edit: Those numbers are for Chrome on my machine. In Firefox there is no significant difference between an unexercised try and no protection at all. There's essentially zero penalty to using try/catch if no exception is thrown.