Javascript Performance: While vs For Loops

后端 未结 5 1776
旧巷少年郎
旧巷少年郎 2020-12-04 14:29

The other day during a tech interview, one of the question asked was \"how can you optimize Javascript code\"?

To my own surprise, he told me that while loops were

5条回答
  •  广开言路
    2020-12-04 15:05

    2016 Answer

    In JavaScript the reverse for loop is the fastest. For loops are trivially faster than while loops. Be more focused on readability.

    Here is some bench marking.

    The following loops where tested:

    var i,
      len = 100000,
      lenRev = len - 1;
    
    i = 0;
    while (i < len) {
        1 + 1;
        i += 1;
    }
    
    i = lenRev;
    while (-1 < i) {
        1 + 1;
        i -= 1;
    }
    
    for (i = 0; i < len; i += 1) {
        1 + 1;
    }
    
    for (i = lenRev; - 1 < i; i -= 1) {
        1 + 1;
    }
    

提交回复
热议问题