[removed] What's more efficient, IF block or TRY/CATCH?

前端 未结 7 1256
忘了有多久
忘了有多久 2020-12-14 08:55

I\'d love some other opinions on what\'s more efficient in this code. Basically in the following code, there\'s a setInterval loop and I need 4 requirements to be true befor

7条回答
  •  既然无缘
    2020-12-14 09:24

    For the provided example where you are wrapping a try/catch around a block of code that should always run anyway (unless if something horrible happens), it is good form to use try/catch. An analogy for you: do you always test "Is the sky Blue?" in your if statement, or would you wrap it in a try/catch that is triggered only when the sky happens to turn Green.

    Use the If statement method if you are dealing with user provided input or if the chances of a function not existing is much higher due to something else happening in the code.

    Keep in mind that if you don't trigger the exception you don't have any unwinding or backtracking across code. In the example the catch will only execute if something is wrong (jQuery is missing or some such thing), however the if statement method has an evaluation happening on EVERY SINGLE CALL to that function - you shouldn't do more work than you have to.

提交回复
热议问题