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 20 functions which have try-catch blocks in them and another function that calls every one of those 20 functions where none of them throw an exception. Will my code execute slower or perform much worse because of this try-catch blocks?
Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.
If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch
:
function tryCatch(fun) {
try {
return fun();
}
catch(e) {
tryCatch.errorObj.e = e;
return tryCatch.errorObj;
}
}
tryCatch.errorObj = {e: null};
var result = tryCatch(someFunctionThatCouldThrow);
if(result === tryCatch.errorObj) {
//The function threw
var e = result.e;
}
else {
//result is the returned value
}
After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch
is the same as that of normal code.