DHTML and JavaScript Performance Tuning

Using JavaScript

Loops

  1. Limit Work Inside Loops
  2. Precalculate Length
  3. Favor Iteration Over Recursion
  1. Limit Work Inside Loops

    Anytime you can eliminate a procedure inside of a loop, do it. See tip 2: Shorten object chains.

    The amount of performance benefit gained will be equivalent to (procudure_duration × number_of_iterations) - 1.

    If a procedure in a loop takes 30ms and the loop iterates 20 times, that translates to 570ms in wasted processing.

    Limit Work Inside Loops
    Ease Effectiveness Overall Practicality
    9
    M IE S Op
    10 10 10 10
    10
  2. Precalculate Length

    for(var i = 0; i < collection.length; i++){
    }
    

    Can be more efficiently written as:

    for(var i = 0, len = collection.length; i < len; i++){
    }
    
    Precalculate Length
    Ease Effectiveness Overall Practicality
    9
    M IE S Op
    1 1 1 1
    8

    Demo ->

    Precalculate Loop Length

      Precalculating the length of a loop will have a minimal effect per iteration, in most cases. If the length variable is reused in the body of the loop, the benefit will be greater. It is very easy to do and doesn't obfuscate the code, so we just do it anyway.

  3. Favor Iteration Over Recursion

    Iterative solutions are usually (not always) more efficient. Sometimes a recursive solution is the only natural solution. When an iterative solution to a recursive problem gets confusing, it is okay to stick to recursion.

    Favor Iteration Over Recursion
    Ease Effectiveness Overall Practicality
    2
    M IE S Op
    Varies
    3

    Demo ->

    Favor Iteration Over Recursion.

     

Next in this tutorial:

 

*AnimTree
*Tabs
*GlideMenus
*DragLib