Possible Duplicate:
Javascript Try-Catch Performance Vs. Error Checking Code
A colleague of mine told me that using a lot of try catch blocks in javascript is going to be a hit in performance . Is that claim true and if yes then why ?
Possible Duplicate:
Javascript Try-Catch Performance Vs. Error Checking Code
A colleague of mine told me that using a lot of try catch blocks in javascript is going to be a hit in performance . Is that claim true and if yes then why ?
Short answer, yes he is correct. A try/catch
statement has do to certain things under the hood in order to work. For instance, it will extend the scope lookup chain (which might not be that big problem in modern environments) but it especially needs to evaluate whatever code is within that try-block
, to figure if there are any errors thrown.
Anyway, try/catch
blocks are a great opportunity to make your code stable. However, you should always apply it on the smallest fraction of your code possible and of course only, if it is really needed (like, avoiding browser specific bugs/errors which you can't work around). Just putting like all of your script into one big try/catch
block, is certainly the worst idea.
Yes. There is a good article on that at dev.opera.com.
This is likely because try-catch-blocks have that certain, unusual handling of result objects, they need to check whether its type is throw
. And then, executing the catch
block is not as easy as it looks in the code. See Ecmascript §12.14: The try
Statement for further reading.
Still, try-catch-clauses are a powerful feature, and one should use them where appropriate and useful. But instead of having them inside performance-critical functions, you should wrap them around so they are not executed too often.