High-performance JavaScript loop statements and conditional statements, and high-performance javascript

Source: Internet
Author: User

High-performance JavaScript loop statements and conditional statements, and high-performance javascript

I. Cyclic statements
As we all know, common loop statements include for, while, do-while, for-in, and forEach. In addition to the for-in and forEach performance, we usually choose the first three based on requirements rather than performance considerations. Today we will test their respective performance, it tells us what optimization can be done in the most extreme situations.

First, let's talk about why for-in and forEach are slower than others. Generally, for-in is used to traverse object attribute names. Because each iteration searches for the attributes of the instance and the attributes of the prototype chain at the same time, the efficiency must be low; forEach is a function-based iteration (it is important to note that all versions of ie do not support it. If necessary, you can use libraries such as JQuery ), the overhead of calling an external method for each array item is the main cause of slow speed.

Next, let's take a look at what is done in each iteration for, while, and do-while.

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 of the above loops, this operation is performed each time the loop body is run:

  • Compare the values in one control condition (I <length)
  • Compare whether the results of one control condition are true (I <length = true)
  • One auto-increment operation (I ++)
  • An array query (items [I])
  • Invoke function call process (items [I])

We can improve the loop Performance by reversing the order of 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, an inverted loop is used, and the subtraction operation is integrated into the cyclic condition. Now each control condition is simply compared with 0. When the control condition is compared with the true value, any non-zero number is automatically converted to true, and the zero value is equivalent to false. In fact, the control condition is compared from two (is the number of iterations less than the total number? Is it true ?) Reduce to a single comparison (is it true ?). Each iteration is reduced from two comparisons to one, further improving the cycle speed.

Performance test:

Is that true? Jin is not afraid of browser verification. The test code is very simple. Eight functions are encapsulated for different 8 cases (the profiles information cannot be printed in firefox without a timer. The reason is unknown ):

// init arrayvar 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 array length is 100, we find that the results in firefox are indeed similar to expected: for-each and for-in are inefficient, and the reverse order is slightly more efficient than the forward order. (Profiles in chrome are not displayed because the time is too short)

When the data volume reaches, The results in firefox and chrome are as expected, but they are slightly different. The for-in ff is better than for-each, while the for-in chrome is worse, and a warning is raised directly. Although the performance of reverse iteration is slightly improved, there are not many improvements and the code reading is reduced.

Summary:

  • Reverse iteration Can slightly improve the Code performance, but at the cost of code readability, unless the pursuit of extreme performance optimization is not necessary
  • Do not use for-in or for-each to traverse an array.

Ii. conditional statements
Common condition statements include if-else and switch-case. When can I use if-else and switch-case?

Let's first look at the code of a simple if-else statement:

if (value == 0){  return result0;} else if (value == 1){  return result1;} else if (value == 2){  return 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){  return result8;} else if (value == 9){  return result9;} else {  return result10;}

In the worst case (value = 10), we may make 10 judgments to return the correct results. How can we optimize this code? An obvious optimization strategy is to determine the most likely values in advance. For example, if the value is the most likely to be 5 or 10, the two judgments should be made in advance. However, we usually do not know (the most likely choice). In this case, we can adopt a binary tree search 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;    }  }} else {  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;    }  }}

After this optimization, we can make up to four judgments, greatly improving the code performance. This optimization idea is a bit similar to binary search. Like binary search, this optimization can be performed only when the value is a continuous number. However, writing code like this is not conducive to maintenance. If you want to add one or more conditions, you need to rewrite a lot of code. Then the switch-case statement is 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 overwrite the return part of the code. Generally, when the number of cases reaches a certain number, swtich-case statements are more efficient than if-else statements, because switch-case uses branch table indexes for optimization, of course, different browsers have different levels of optimization.

In addition to if-else and swtich-case, we can also use the lookup table.

var results = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];//return the correct resultreturn results[value];

When the data volume is large, the efficiency of table searching is usually higher than that of the if-else statement and the swtich-case statement. The table searching can be indexed by numbers and strings, in the case of a string, it is best to use an object instead of an array. Of course, the use of table searching has limitations. The result of each case can only be a value, not a series of operations.

Summary:

  • When only two case or case values are consecutive numbers, we can select the if-else statement.
  • When there are 3 ~ When there are 10 cases and the case value is non-linear, we can select the switch-case statement.
  • When the number of cases is more than 10 and each result is only a value, rather than an additional JavaScript statement, we can choose to find the table

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Differences in the usage of javascript loop statements while, do-while, for-in, and
  • A deep understanding of the for statements in javascript
  • Optimization Techniques of cyclic statements in JavaScript
  • Basic Javascript tutorial-if condition statements

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.