Skip to content

Instantly share code, notes, and snippets.

@thurt
Last active January 25, 2016 17:25
Show Gist options
  • Save thurt/4c45f41f211852898983 to your computer and use it in GitHub Desktop.
Save thurt/4c45f41f211852898983 to your computer and use it in GitHub Desktop.
Performance of if else vs try catch
function if_else() {
if (window.foo) {
window.foo.bar = 'never gets here because we explicitly checked for window.foo first'
} else {}
}
// this will always be slower because it creates an exception
// and then navigates that exception to the first catch block
function try_catch() {
try {
window.foo.bar = 'cant assign'
} catch(err) {}
}
@thurt
Copy link
Author

thurt commented Jan 25, 2016

RE: http://jsperf.com/if-vs-try-catch-performance-comparison/2

Please note: measuring speed performance between if/else and try/catch does not make any sense to me. This is because try/catch and if/else cover different usage domains!

The point of try/catch is that you expect there could be an error but you aren't sure exactly what that error will be before hand, or there are too many possible errors for you to explicitly check every single one. A good example would be JSON.parse (we know there could be a syntax error somewhere in the JSON but we don't know the exact syntax errors to check for).

If/else CAN be used for error checking--but when used in this domain it is not guaranteed that you can recover gracefully. In order to recover gracefully, you would have to create if/else checks to directly and explicitly check for EVERY possible error condition, otherwise some errors could "fall through the cracks" and become uncaught exceptions. Checking for errors with an if/else statement means that you KNOW the expected error condition ahead of time and you are explicitly testing for it and rerouting to avoid it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment