_javascript techniques for high performance JavaScript looping statements and conditional statements

Source: Internet
Author: User
Tags case statement

One, circular statement
as we all know, the commonly used loop statements are for, while, Do-while, and For-in,foreach. In addition to the for-in and foreach performance slightly lower, usually our choice of the first three is more based on requirements rather than performance considerations, today we have their own performance test, tell us the most extreme circumstances can also do what optimization.

First, let's talk about why For-in and foreach are slower than others. For-in are generally used in the traversal of object property names, and because each iteration will search both the properties of the instance itself and the attributes on the prototype chain, the efficiency is certainly low; foreach is a function-based iteration (it should be noted that all versions of IE are not supported, If you need to be able to use a library like jquery, the overhead of calling an external method on each array item is the main reason for the slow speed.

Then we look at what the for, while, and Do-while do in each iteration.

var length = items.length;
for (var i = 0; i < length; i++)
 process (items[i]);

var j = 0;
while (J < length) 
 process (items[j++]);

var k = 0;
Do {
 process (items[k++]), while
(K < length);

In each loop above, each time the loop body is run, this action occurs:

    • Numeric size comparisons in a single control condition (I < length)
    • A comparison that controls whether the condition result is true at once (i < length = = True)
    • One self-augmentation operation (i++)
    • One-time array lookup (Items[i])
    • One function call process (Items[i])

We can improve cyclic performance by reversing the order of the arrays:

for (var i = items.length; i--;)
 Process (Items[i]);

var j = items.length;
while (j--) 
 process (items[j]);

var k = items.length-1;
Do {
 process (items[k]);
} while (k--);

In this example, the reverse loop is used and the subtraction operation is consolidated in the loop condition. Now each control condition is simply compared to 0. Control conditions are compared to true values, and any zero are automatically converted to true, and 0 values are equivalent to false. In fact, are control conditions from two comparisons (the number of iterations is less?). Is it true? Reduced to one comparison (is it true?) )。 Each iteration is reduced from two to one, further increasing the cycle speed.

Performance test:

So is that really the case? True gold is not afraid of browser inspection. The test code is very simple, for different 8 kinds of cases encapsulated 8 functions (without the timer Firefox cannot print profiles information, unexplained):

Init array var a = [];
var length = 10;

for (var i = 0; i < length; i++) a[i] = 1;
 function for_in () {var sum = 0;
for (var i in a) sum + = A[i];
 function For_each () {var sum = 0;
 A.foreach (function (value, index, array) {sum = value;
});
 function For_normal () {var sum = 0;
for (var i = 0; i < length; i++) sum + = A[i];
 function For_reverse () {var sum = 0;
  for (var i = length; i--;)
Sum + + a[i];
 function While_normal () {var sum = 0;
 var i = 0;
while (i < length) sum + = a[i++];
 function While_reverse () {var sum = 0;
 var i = length;
while (i--) sum + = A[i];
 function Do_while_normal () {var sum = 0;
 var i = 0;
 do {sum = a[i++];
while (i < length);
 function Do_while_reverse () {var sum = 0;
 var i = length-1;
 do {sum = A[i];
while (i--);
 } settimeout (function () {console.profile ();
 For_in ();
 For_each ();  
 For_normal ();
 For_reverse ();
 While_normal ();
 While_reverse ();
 Do_while_normal (); Do_while_reverse ();
Console.profileend ();

 }, 1000);

When the length of the array is 100, we find that the results under Firefox are exactly the same as expected: For-each and for-in are inefficient, and the reverse is slightly higher than the positive sequence efficiency. (Chrome profiles because time is too short to show)

When the amount of data reaches 100w, the results under Firefox and Chrome are as people wish, but slightly different. FF for-in performance than For-each, and chrome for-in performance is poor, direct warning. While the reverse iterations have slightly improved performance, they are not much improved and the code reading is reduced.

Summary:

    • Reverse iterations do slightly improve code performance, but at the expense of code readability, it is not necessary to pursue extreme performance optimizations
    • Traversing an array can use a normal loop instead of for-in and For-each.

Second, conditional statements
Common conditional statements have If-else and switch-case, then when to use If-else, when to use the Switch-case statement?

Let's take a look at the code for a simple If-else statement:

if (value = = 0) {return
  result0;
} else if (value = = 1) {return
  result1;
} else if (value = = 2) {
  retur n result2;
} else if (value = = 3) {return
  RESULT3
} else if (value = = 4) {return
  result4;
} else if (value = = 5) {
   return result5;
} else if (value = = 6) {return
  result6
} else if (value = = 7) {return
  result7;
} else if (value = = 8) { C17/>return result8;
} else if (value = = 9) {return
  result9;
} else {return
  result10;
}

In the worst case (value=10) we may have to make 10 judgements to return the correct result, so how do we optimize this code? An obvious optimization strategy is to determine the most probable value in advance, such as value is the most likely to be 5 or 10, then advance the two judgments. But usually we do not know (the most likely choice), then we can take the binary tree lookup strategy for performance optimization.

if (Value < 6) {
  if (value < 3) {
    if (value = = 0) {return
      result0;
    } else if (value = = 1) {
      return RESULT1;
    } else {return
      result2;
    }
  } else {
    if (value = = 3) {return
      result3;
    } else if (value = = 4) {
   
    return result4;
    } else {return
      result5
    }}
{
  if (value < 8) {
    if (value = = 6)
      {return result6 ;
    } else {return
      result7;
    }
  } else {
    if (value = = 8) {return
      result8;
    } else if (value = = 9) {
    return result9;
    } else {return
      result10;
    }
  }
}

   

In this way, we can make a maximum of 4 judgments, which greatly improves the performance of the code. Such an optimization idea is somewhat similar to a binary lookup, and similar to a binary lookup, this optimization can only be done if the value is a sequential number. But the code written in this way is not conducive to maintenance, if you want to add a condition, or multiple conditions, you need to rewrite a lot of code, then Switch-case statement has a useful.

Rewrite the above code with the Switch-case statement:

Switch (value) {case
  0: return
    result0;
  Case 1: Return
    result1;
  Case 2: Return
    result2;
  Case 3: Return
    RESULT3;
  Case 4: Return
    RESULT4;
  Case 5: Return
    RESULT5;
  Case 6: Return
    result6;
  Case 7: Return
    result7;
  Case 8: Return
    result8;
  Case 9: Return
    result9;
  Default: Return
    result10;
}

The Swtich-case statement makes the code more readable, and the Swtich-case statement also has the advantage that if multiple value values return the same result, you do not need to rewrite the code for that part. Generally speaking, when the case number reaches a certain number, the Swtich-case statement efficiency is higher than the if-else, because Switch-case uses the branch table (the Branch table) index to carry on the optimization, certainly each browser's optimization degree also is different.

In addition to If-else and swtich-case, we can also use lookup tables.

var results = [Result0, RESULT1, Result2, RESULT3, Result4, RESULT5, Result6, Result7, Result8, Result9, result10];

Return of the correct result return
Results[value];

When data volumes are large, look-up tables are generally more efficient than if-else statements and swtich-case statements, and lookup tables can be indexed by numbers and strings, and in the case of strings, it is better to use objects instead of arrays. Of course, the use of look-up table is limited, each case corresponding to the result can only be a value but not a series of operations.

Summary:

    • When only two cases or the value of the case is a continuous number, we can select the If-else statement
    • When there is a 3~10 case number and the value of the case is non-linear, we can select the Switch-case statement
    • When the case number reaches more than 10 and each time the result is a value instead of an extra JavaScript statement, we can choose to find the table

The above is the entire content of this article, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.