Use of try-catch in JavaScript

前端 未结 4 439
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 15:26

How time-intensive is the use of try/catch in JavaScript? I have an application and I am using it in a function which is called a few hundred times. N

相关标签:
4条回答
  • 2021-02-05 15:39

    There are some nice tests on jsPref:

    • http://jsperf.com/try-catch-performance-overhead
    • http://jsperf.com/try-catch-versus-massive-if
    • http://jsperf.com/try-catch-002

    Conclusion: on the major browser, null to minimal differences.

    0 讨论(0)
  • 2021-02-05 15:41

    You should take note of the following:

    “The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson

    I've wasted time optimising sections of code that had little impact on performance. Make sure you know what is slow by running some timing experiments.

    0 讨论(0)
  • 2021-02-05 15:52

    In general, code executed inside a try block is expensive. But if you are invoking a try block on the order of a few hundred times, it's probably not an issue. If it were a few hundred thousand, you may want to re-think your design.

    0 讨论(0)
  • 2021-02-05 15:58

    The try/catch clause creates a new scope in javascript, so every variable that has to come from the parent scope will be slightly slower.

    The overhead isn't that great but too large to completely ignore for your inner loops.

    Take a look at this video for a more in-depth explanation: http://www.youtube.com/watch?v=mHtdZgou0qU

    0 讨论(0)
提交回复
热议问题