23 Practical Skills to Improve the Execution Efficiency of JavaScript

  • 2021-07-24 10:12:20
  • OfStack

This article shares 23 JavaScript tips, best practices and other very practical contents to improve the execution efficiency. Of course, the practical skills of JavaScript are not only these, but also many fun skills that can improve the efficiency of the program. We will continue to share them with you in the future.

The code snippets provided in this article have been tested with the latest version of Chrome 30, which uses the V 8 JavaScript engine (V 8 3.20. 17.15).

STEP 1 Use logical symbols & & Or make conditional judgments


var foo = 10; 
foo == 10 && doSomething(); //  If  foo == 10  Execute the  doSomething(); 
foo == 5 || doSomething(); //  If  foo != 5  Execute the doSomething(); 

'' can also be used to set default values for function arguments


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}

2. Use the map () method to traverse an array


var squares = [1,2,3,4].map(function (val) { 
 return val * val; 
}); 
//  The running result is  [1, 4, 9, 16]

3. Rounding decimal places


var num =2.443242342; 
num = num.toFixed(4); //  Reservation 4 Decimal bits  2.4432

4. Floating-point number problem


0.1 + 0.2 === 0.3 // is false 
9007199254740992 + 1 // = 9007199254740992 
9007199254740992 + 2 // = 9007199254740994

0.1 +0.2 equals 0.3000000000000004. Why does this happen? According to the IEEE 754 standard, you need to know that all JavaScript digits in 64-bit binary represent floating-point numbers. Developers can use the toFixed () and toPrecision () methods to solve this problem.

5. Check traversal object properties using for-in loop

The following code is mainly to avoid traversing object properties.


for (var name in object) { 
 if (object.hasOwnProperty(name)) { 
  //  Execute code 
 } 
}

6. The comma operator


var a = 0; 
var b = ( a++, 99 ); 
console.log(a); // a  For  1 
console.log(b); // b  For  99

7. Evaluate or query cache variables

With the jQuery selector, developers can cache DOM elements


var navright = document.querySelector('#right'); 
var navleft = document.querySelector('#left'); 
var navup = document.querySelector('#up'); 
var navdown = document.querySelector('#down'); 

8. Validate parameters before passing them to isFinite ()


isFinite(0/0) ; // false 
isFinite("foo"); // false 
isFinite("10"); // true 
isFinite(10); // true 
isFinite(undifined); // false 
isFinite(); // false 
isFinite(null); // true !!!

9. Avoid negative indexing in arrays


var numbersArray = [1,2,3,4,5]; 
var from = numbersArray.indexOf("foo") ; // from is equal to -1 
numbersArray.splice(from,2); // will return [5]

Ensure that the parameters passed into the indexOf () method are non-negative.

10. Serialization and deserialization (using JSON)


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
0

11. Avoid using eval () or Function constructors

The eval () and Function constructors are called script engines, and each time they are executed, the source code must be converted into executable code, which is an expensive operation.


var func1 = new Function(functionCode); 
var func2 = eval(functionCode);

12. Avoid using the with () method

If you use with () to insert a variable in a global zone, it is easy to confuse and override a variable that has a variable name like its name.

13. Avoid using for-in loop in arrays

Instead of using it like this:


var sum = 0; 
for (var i in arrayNumbers) { 
 sum += arrayNumbers[i]; 
}

This will be better:


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
3

Because i and len are the first statements in the loop, each instantiation is executed once, which is faster than the following:


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
4

Why? The array length arraynNumbers is recalculated at each loop iteration.

14. Do not pass strings into setTimeout () and setInterval () methods

If you pass a string in both methods, the string will be recalculated like eval, so that the speed will be slower, instead of using this:


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
5

On the contrary, it should be used as follows:


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
6

15. Use the switch/case statement instead of the longer if/else statement

If you have more than 2 case, then using switch/case is much faster and the code looks more elegant.

16. You can choose switch/casne when you encounter a numerical range


function getCategory(age) { 
 var category = ""; 
 switch (true) { 
  case isNaN(age): 
   category = "not an age"; 
   break; 
  case (age >= 50): 
   category = "Old"; 
   break; 
  case (age <= 20): 
   category = "Baby"; 
   break; 
  default: 
   category = "Young"; 
   break; 
 }; 
 return category; 
} 
getCategory(5); //  Return  "Baby"

17. Create an object whose properties are a given object

You can write a function like this to create an object whose property is a given object, like this:


function clone(object) { 
 function OneShotConstructor(){}; 
 OneShotConstructor.prototype= object; 
 return new OneShotConstructor(); 
} 
clone(Array).prototype ; // []

18.1 HTML escaper functions


Function doSomething(arg1){ 
 Arg1 = arg1 || 10; //  If  arg1 To set the  Arg1=10
}
9

19. Avoid try-catch-finally in 1 loop

try-catch-finally creates a new variable when it runs in the current scope, and when catch is executed, the catch exception object is assigned to the variable.
Do not use:


var object = ['foo', 'bar'], i; 
for (i = 0, len = object.length; i <len; i++) { 
 try { 
  //  Execute the code, and if there is an error, it will be caught 
 } 
 catch (e) {  
  //  Get the error and execute the code 
 } 
}

It should be used as follows:


var object = ['foo', 'bar'], i; 
try { 
 for (i = 0, len = object.length; i <len; i++) { 
  //  Execute the code, and if there is an error, it will be caught 
 } 
} 
catch (e) {  
 //  Get the error and execute the code 
}

20. Set timeouts for XMLHttpRequests

If an XHR takes too long, you can terminate the link (e.g. network problems) and fix it by using setTimeout () for XHR.


var xhr = new XMLHttpRequest (); 
xhr.onreadystatechange = function () { 
 if (this.readyState == 4) { 
  clearTimeout(timeout); 
  //  Execute code 
 } 
} 
var timeout = setTimeout( function () { 
 xhr.abort(); // call error callback 
}, 60*1000 /*  Settings 1 Execute in minutes */ ); 
xhr.open('GET', url, true); 
 
xhr.send();

In addition, you should generally avoid synchronizing Ajax calls altogether.

21. Processing WebSocket timeout

1 Generally speaking, when creating an WebSocket link, the server may time out after 30 seconds of idleness, and the firewall may time out after 1 period of idleness.

To solve this timeout problem, you can regularly send empty information to the server and add two functions to the code: one to keep link 1 alive and one to unlink it alive. In this way, you will control the timeout problem.

Add 1 ES180 EN … …


var timerID = 0; 
function keepAlive() { 
 var timeout = 15000; 
 if (webSocket.readyState == webSocket.OPEN) { 
  webSocket.send(''); 
 } 
 timerId = setTimeout(keepAlive, timeout); 
} 
function cancelKeepAlive() { 
 if (timerId) { 
  cancelTimeout(timerId); 
 } 
}

The keepAlive () method should be added at the end of the WebSocket link method onOpen (), and the cancelKeepAlive () method should be placed under the onClose () method.

22. Remember, primitive operations are faster than function calls

For simple tasks, it is best to use basic operations instead of function calls.
For example


var min = Math.min(a,b); 
A.push(v);

Basic operation mode:


var min = a < b ? a b; 
A[A.length] = v;

23. Pay attention to the beauty and readability of the code when coding

JavaScript is a very good language, especially for front-end engineers, JavaScript execution efficiency is also very important.

When we write JavaScript program, we should pay attention to some small details and master some common practical skills, which will often make the program simpler and more efficient


Related articles: