Javascript Try-Catch Performance Vs. Error Checking Code

前端 未结 7 1817
萌比男神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:34

    Depends on the situation. As galambalazs mentions readability is important. Consider:

    function getCustomer (id) {
      if (typeof data!='undefined' && data.stores && data.stores.customers 
          && typeof data.stores.customers.getById=='function') {
        return data.stores.customers.getById(id);
      } else {
        return null;
      }
    }
    

    compared to:

    function getCustomer (id) {
      try {return data.stores.customers.getById(id);} catch (e) { return null; }
    }
    

    I'd say the second is much more readable. You tend to get data back like this from things like google's apis or twitter's feeds (usually not with deeply nested methods though, that's just here for demonstration).

    Of course, performance is also important, but these days javascript engines are fast enough that nobody's likely to notice a difference, unless you're going to call getCustomer every ten milliseconds or something.

提交回复
热议问题