Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ High-performance JavaScript loops and flow control     - Ubuntu 14.04 installed VirtualBox 4.3 appears vboxdrv: Unknown symbol mcount (Linux)

- Oracle 11g forget approach SYS and SYSTEM password (Database)

- Linux system commands to view hardware information (Linux)

- RHEL5 establish a local yum source (Linux)

- Deployment Kubernetes manage Docker example cluster on Ubuntu (Server)

- Linux environment variable configuration and save places (Linux)

- Elementary OS Freya global menu (Linux)

- Install JDK 1.7 + Eclipse in CentOS 6.4 in (Linux)

- Kibana Apache Password Authentication (Server)

- MySQL and MariaDB traditional master-slave cluster configuration (Database)

- Introduction and bash history command to quickly call (Linux)

- GitLab issued Merge Request return error 500 when the two solutions log (Linux)

- Ubuntu 14.04 installation and configuration environment variable JDK1.8.0_25 (Linux)

- Installation and configuration under Linux SVN server - Backup - Recovery - Scheduled Tasks (Server)

- PL / SQL data types (Database)

- Use Git in Eclipse (Linux)

- Ubuntu 14.10 / Linux Mint 17.1 Win10 compiler install rdesktop 1.8.3 Remote Desktop connection (Linux)

- Redis is installed in Ubuntu 14.04 (Database)

- Editor of the popular Linux Gvim (Linux)

- PostgreSQL Source Customization: Online global read only (Database)

 
         
  High-performance JavaScript loops and flow control
     
  Add Date : 2017-04-13      
         
         
         
  Foreword

Previous discusses JavaScript Duff's device for the performance of the code, and test a variety of paper mainly discusses the performance and optimization of process control common common looping statement.

Loops

As we all know, there are commonly used loop for, while, do-while and for-in, forEach. In addition to for-in and forEach performance is slightly lower, but usually our first three choices based more on demand rather than performance reasons, today we have to be on their own performance tests, tell us the most extreme cases, What do optimization.

First, let's talk about why for-in and forEach slower than others. for-in is generally used on the object attribute name traversal, since each iteration operation while searching for attributes and attribute instance itself prototype chain, so certainly low efficiency; while forEach is based on iterative function (requires special attention It is that all versions ie do not support, you can use if you need libraries like JQuery), for each array item to call an external method the overhead is the main reason for slow.

Then we look at each iteration for, while and do-while do something.

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);
Each cycle in the above, when you run the loop body will produce each such operation:

A control condition in numerical size comparison (< length)
A control condition result of a comparison to true (i < length === true)
One increment operator (i ++)
An array search (items [i])
A function call process (items [i])
We can improve cycling performance by reverse the order of the array:

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--);
This example uses a reverse cycle, the subtraction operation and integration in the loop condition. Now each control condition simply compared with 0. Compared with the true value of the control condition, any non-zero number will be automatically converted to true, while a value of zero is equivalent to false. In fact, from two relatively controlled conditions (less than the total number of iterations? Is it true it?) Is reduced to a comparative (it is true it?). Compare each iteration is reduced from two to one, and further improve the cycle speed.

Performance Testing:

So this really true? True gold fears browser experience. Test code is very simple, for eight different kinds of situations package of eight functions (without information can not be printed profiles Timer firefox, for unknown reasons):

// 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 found that the results of firefox and indeed expected under similar: for-each low and for-in efficiency, descending slightly to enhance efficiency than the positive sequence. (Profiles chrome under such a short time is not displayed)

When the data reaches 100w, results firefox and chrome are under as we wish, but slightly different. for-in performance ff under than for-each well, and chrome under the for-in poor performance directly warned. The reverse iterations although performance has improved slightly, but not a lot of improvement, and reduces code readability.

 summary:

Reverse iteration can really enhance the performance of your code slightly, but at the expense of code readability, unless the pursuit of extreme performance optimization case otherwise no need to use
Common loop through the array can not use the for-in and for-each
Conditional statements

Common conditional statements have if-else and switch-case, then when to use if-else, when to use switch-case statement is it?

First look at a simple if-else statements code that we:

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;
}
The worst case (value = 10), we may need to do 10 times a judge to return the correct results, then how do we optimize this code? One obvious strategy is to optimize the most probable value is determined in advance, such as the most probable value is equal to 5 or 10, so these two judgments in advance. But often we do not know (most likely option), then we can take the binary tree search strategy to optimize performance.

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 optimization so we can determine up to four times, greatly improving the performance of the code. Such optimization is somewhat similar ideological binary search and binary search is similar, only the value of such value is to be optimized when consecutive numbers. But the code written words are not conducive to the maintenance, if you want to add a condition or multiple conditions, it is necessary to rewrite a lot of code, then the switch-case statement comes into play.

The above code rewritten 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;
}
swtich-case statement to make the code more readable look, but swtich-case statement that there is a benefit if more than one value is the value returned by the same result, would not return to rewrite that part of the code. Generally, when the case reaches a certain number, efficiency swtich-case statement is higher than the if-else, switch-case because using a branch table (branch tables) to optimize the index, of course, the degree of optimization of each browser not the same.

Except if-else and swtich-case, we can also use a lookup table.

var results = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];

// Return the correct result
return results [value];
When large amounts of data when the lookup table is usually efficient than if-else statements and swtich-case statement is high, lookup tables can be used as the index numbers and strings, and if it is the case of the string, it is best to use the object instead of an array. Of course, using a lookup table are limited, the results corresponding to each case can only be a value can not be a series of operations.

summary:

When only two case or the case of the value argument is the time period of consecutive numbers, we can choose if-else statements
When 3 to 10 case number and value of the value of non-linear case, we can choose to switch-case statement
When the case reached 10 or more, and each time the result is a value instead of extra JavaScript statements, we can choose a lookup table.
     
         
         
         
  More:      
 
- How to install new fonts on Ubuntu 14.04 and 14.10 (Linux)
- Using IE can also be easily remotely control the computer (Linux)
- Oracle how to assess the true concurrent session (Database)
- How Linux system password security guarantee (Linux)
- Drawing from the Android source code analysis View (Programming)
- Zabbix monitoring tool deployment under Ubuntu server (Server)
- impdp error ORA-31631, ORA-39122 (Database)
- Linux file time Comments ctime mtime atime (Linux)
- CentOS and RHEL to install IPython 0.11 (Linux)
- Linux systems for entry-learning - Install Go language in Linux (Linux)
- Python Dir find a folder several files (Programming)
- Linux iptables: Composition Rules (Linux)
- Using Ruby to build a simple HTTP service and sass environment (Server)
- Intruder tools Knark Analysis and Prevention Linux environment (Linux)
- MySQL error: ERROR 1175: You are using safe update mode solution (Database)
- Linux iptables firewall and vsftpd to resolve the issue (Linux)
- Export error: ORA-04063: package body dmsys dbms dm model exp has error (Database)
- php for Linux the MySQL extension module installation and configuration (Database)
- 20 Linux commands interview questions and answers (Linux)
- Ubuntu install video conversion tool Selene (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.