Javascript Try-Catch Performance Vs. Error Checking Code

前端 未结 7 1818
萌比男神i
萌比男神i 2020-11-28 09:56

Would it be faster to just put code inside a try-catch block instead of performing various error checks?

For example..

function getProjectTask(projec         


        
7条回答
  •  天涯浪人
    2020-11-28 10:27

    Placing dogma aside and not being satisfied with the answers here at the moment...

    If your code rarely throws exceptions, placing a try-catch around the offender performs well because there is no additional overhead in catching the exception or preventing it.

    If the code commonly throws exceptions based on unpredictable data or some scenario similar to that, placing a guard method increases performance considerably, up to 20 times if exceptions occur often.

    If I were to advise an approach, use simple guard operators when possible if there isn't deep nesting. In cases of deeper nesting, use a guard method that can traverse through as needed.

    Here's some testing of my own that I based this off of.

    http://jsfiddle.net/92cp97pc/6/

    Scenarios are comparing the following but in loops:

    var a;
    
    // scenario 1 (always throws/catches)
    try { a.b.c.d; }
    catch(ex) { }
    
    // scenario 2 (about 20 times faster than scenario 1)
    guard(a, 'b', 'c', 'd');
    
    // now no exceptions will occur
    a = { b: { c: { d: true } } };
    
    // scenario 3 (too fast to measure)
    try { a.b.c.d; }
    catch(ex) { }
    
    // scenario 4 (.04 times slower than scenario 3)
    guard(a, 'b', 'c', 'd');
    

提交回复
热议问题