Javascript Try-Catch Performance Vs. Error Checking Code

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

    "Programs must be written for people to read, and only incidentally for machines to execute."

    Abelson & Sussman, SICP, preface to the first edition

    Always aim for readable code. The key thing to remember is:

    Avoid try-catch in performance-critical functions, and loops

    Anywhere else they won't do much harm. Use them wisely, use them sparingly. As a side note if you want to support older browsers they may not have try-catch.

    But as I see you clearly misuse some functions for error checking. You can test for the desired objects and properties of objects right before you use them instead of complex checking. And:

    if (YAHOO.lang.isUndefined(projectPhaseId) || YAHOO.lang.isNull(projectPhaseId))
    

    can be written as

    if (projectPhaseId != null)
    

    for example... So the example above can be fairly readable even without try catches. You seem to misuse YUI a bit.

    I would bet this works as expected:

    function getProjectTask(projectTaskId) {
    
       var projectPhaseId    = projectTaskPhaseMap[projectTaskId],
           projectPhaseIndex = scheduleData.ProjectPhasesMap[projectPhaseId],
           projectPhase      = scheduleData.ProjectPhases[projectPhaseIndex];
    
      if (projectPhase == null) return null; // projectPhase would break the chain
    
      var projectTaskIndex  = projectPhase.ProjectTasksMap[projectTaskId],
          projectTask       = scheduleData.ProjectTasks[projectTaskIndex];
    
       return projectTask || null; // end of the dependency chain
    
    }
    

    How cool is that? :)

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