Home Web Front-end JS Tutorial Summary of improving JS execution efficiency

Summary of improving JS execution efficiency

Apr 23, 2018 am 10:51 AM
javascript Summarize efficiency

This time I will bring you a summary of how to improve JS execution efficiency and what are the precautions to improve JS execution efficiency. The following is a practical case, let’s take a look.

1. Use logical symbols && or || to make conditional judgments

var foo = 10; 
foo == 10 && doSomething(); // 如果 foo == 10 则执行 doSomething(); 
foo == 5 || doSomething(); // 如果 foo != 5 则执行doSomething();
Copy after login
"||" can also be used to set

functions The default value of the parameter

Function doSomething(arg1){ 
 Arg1 = arg1 || 10; // 如果 arg1为设置那么 Arg1=10
}
Copy after login

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

var squares = [1,2,3,4].map(function (val) { 
 return val * val; 
}); 
// 运行结果为 [1, 4, 9, 16]
Copy after login

3. Rounding to decimal places

var num =2.443242342; 
num = num.toFixed(4); // 保留四位小数位 2.4432
Copy after login

4. Floating point number problem

0.1 + 0.2 === 0.3 // is false 
9007199254740992 + 1 // = 9007199254740992 
9007199254740992 + 2 // = 9007199254740994
Copy after login
0.1 0.2 is equal to 0.30000000000000004. Why does this happen? According to the IEEE754 standard, all you need to know is that all JavaScript numbers are represented as floating point numbers in 64-bit binary. Developers can use toFixed() and toPrecision() methods to solve this problem.

5. Use for-in loop to check the traversed object properties

The following code is mainly to avoid traversing the object properties.

for (var name in object) { 
 if (object.hasOwnProperty(name)) { 
  // 执行代码
 } 
}
Copy after login

6. Comma operator

var a = 0; 
var b = ( a++, 99 ); 
console.log(a); // a 为 1 
console.log(b); // b 为 99
Copy after login

7. Calculate or query cache variables

Developers can cache DOM elements when using jQuery selectors

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

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 !!!
Copy after login

9. Avoid negative indexes 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]
Copy after login
Ensure that the parameters passed to the indexOf() method are non-negative of.

10. Serialization and deserialization (using JSON)

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} }; 
var stringFromPerson = JSON.stringify(person); 
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */ 
var personFromString = JSON.parse(stringFromPerson); 
/* personFromString is equal to person object */
Copy after login

11. Avoid using eval() Or Function constructor

eval() and Function constructor are called script engines. Every time they are executed, the source code must be converted into executable code, which is very expensive. operation.

var func1 = new Function(functionCode); 
var func2 = eval(functionCode);
Copy after login

12. Avoid using the with() method

If you use with() to insert variables in the global area, then, if there is A variable with the same name can be easily confused and rewritten.

13. Avoid using for-in loop in an array

Instead of using it like this:

var sum = 0; 
for (var i in arrayNumbers) { 
 sum += arrayNumbers[i]; 
}
Copy after login
This will be more efficient Good:

var sum = 0; 
for (var i = 0, len = arrayNumbers.length; i < len; i++) { 
 sum += arrayNumbers[i]; 
}
Copy after login

Because i and len are the first statements in the loop, they will be executed once for each instantiation, so the execution will be faster than the following:

for (var i = 0; i < arrayNumbers.length; i++)
Copy after login

Why ? The array length, arrayynNumbers, is recalculated on each loop iteration.

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

If you pass strings to these two methods , then the string will be recalculated like eval, which will be slower. Instead of using it like this:

setInterval(&#39;doSomethingPeriodically()&#39;, 1000); 
setTimeOut(&#39;doSomethingAfterFiveSeconds()&#39;, 5000);
Copy after login

Instead, it should be used like this:

setInterval(doSomethingPeriodically, 1000); 
setTimeOut(doSomethingAfterFiveSeconds, 5000);
Copy after login

15 .Use switch/case statements instead of longer if/else statements

If there are more than 2 cases, then using switch/case will be much faster and the code will look cleaner grace.

16. When encountering a numerical range, you can use switch/casne

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); // 返回 "Baby"
Copy after login

17.Create An object whose properties are a given object

You can write such a function to create an object whose properties are a given object, such as Like this:

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

18. An HTML escaper function

function escapeHTML(text) { 
 var replacements= {"<": "<", ">": ">","&": "&", "\"": """};      
 return text.replace(/[<>&"]/g, function(character) { 
  return replacements[character]; 
 }); 
}
Copy after login

19. Avoid using try- in a loop catch-finally

try-catch-finally在当前范围里运行时会创建一个新的变量,在执行catch时,捕获异常对象会赋值给变量。
不要这样使用:

var object = ['foo', 'bar'], i; 
for (i = 0, len = object.length; i <len; i++) { 
 try { 
  // 执行代码,如果出错将被捕获
 } 
 catch (e) {  
  // 获取错误,并执行代码
 } 
}
Copy after login

应该这样使用:

var object = ['foo', 'bar'], i; 
try { 
 for (i = 0, len = object.length; i <len; i++) { 
  // 执行代码,如果出错将被捕获
 } 
} 
catch (e) {  
 // 获取错误,并执行代码
}
Copy after login

20.给XMLHttpRequests设置timeouts

如果一个XHR需要花费太长时间,你可以终止链接(例如网络问题),通过给XHR使用setTimeout()解决。

var xhr = new XMLHttpRequest (); 
xhr.onreadystatechange = function () { 
 if (this.readyState == 4) { 
  clearTimeout(timeout); 
  // 执行代码
 } 
} 
var timeout = setTimeout( function () { 
 xhr.abort(); // call error callback 
}, 60*1000 /* 设置1分钟后执行*/ ); 
xhr.open('GET', url, true); 
 
xhr.send();
Copy after login

此外,通常你应该完全避免同步Ajax调用。

21.处理WebSocket超时

一般来说,当创建一个WebSocket链接时,服务器可能在闲置30秒后链接超时,在闲置一段时间后,防火墙也可能会链接超时。

为了解决这种超时问题,你可以定期地向服务器发送空信息,在代码里添加两个函数:一个函数用来保持链接一直是活的,另一个用来取消链接是活的,使用这种方法,你将控制超时问题。

添加一个timeID……

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); 
 } 
}
Copy after login

keepAlive()方法应该添加在WebSocket链接方法onOpen()的末端,cancelKeepAlive()方法放在onClose()方法下面。

22.记住,最原始的操作要比函数调用快

对于简单的任务,最好使用基本操作方式来实现,而不是使用函数调用实现。
例如

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

基本操作方式:

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

23.编码时注意代码的美观、可读

JavaScript是一门非常好的语言,尤其对于前端工程师来说,JavaScript执行效率也非常重要。

我们在编写JavaScript程序时注意一些小细节,掌握一些常用的实用小技巧往往会使程序更简捷,程序执行效率更高

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JS中时间单位比较的方法

JS操作JSON详细介绍

The above is the detailed content of Summary of improving JS execution efficiency. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PyCharm Remote Development Practical Guide: Improve Development Efficiency PyCharm Remote Development Practical Guide: Improve Development Efficiency Feb 23, 2024 pm 01:30 PM

PyCharm is a powerful Python integrated development environment (IDE) that is widely used by Python developers for code writing, debugging and project management. In the actual development process, most developers will face different problems, such as how to improve development efficiency, how to collaborate with team members on development, etc. This article will introduce a practical guide to remote development of PyCharm to help developers better use PyCharm for remote development and improve work efficiency. 1. Preparation work in PyCh

Summarize the usage of system() function in Linux system Summarize the usage of system() function in Linux system Feb 23, 2024 pm 06:45 PM

Summary of the system() function under Linux In the Linux system, the system() function is a very commonly used function, which can be used to execute command line commands. This article will introduce the system() function in detail and provide some specific code examples. 1. Basic usage of the system() function. The declaration of the system() function is as follows: intsystem(constchar*command); where the command parameter is a character.

Private deployment of Stable Diffusion to play with AI drawing Private deployment of Stable Diffusion to play with AI drawing Mar 12, 2024 pm 05:49 PM

StableDiffusion is an open source deep learning model. Its main function is to generate high-quality images through text descriptions, and supports functions such as graph generation, model merging, and model training. The operating interface of the model can be seen in the figure below. How to generate a picture. The following is an introduction to the process of creating a picture of a deer drinking water. When generating a picture, it is divided into prompt words and negative prompt words. When entering the prompt words, you must describe it clearly and try to describe the scene, object, style and color you want in detail. . For example, instead of just saying "the deer drinks water", it says "a creek, next to dense trees, and there are deer drinking water next to the creek". The negative prompt words are in the opposite direction. For example: no buildings, no people , no bridges, no fences, and too vague description may lead to inaccurate results.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Master Python to improve work efficiency and quality of life Master Python to improve work efficiency and quality of life Feb 18, 2024 pm 05:57 PM

Title: Python makes life more convenient: Master this language to improve work efficiency and quality of life. As a powerful and easy-to-learn programming language, Python is becoming more and more popular in today's digital era. Not just for writing programs and performing data analysis, Python can also play a huge role in our daily lives. Mastering this language can not only improve work efficiency, but also improve the quality of life. This article will use specific code examples to demonstrate the wide application of Python in life and help readers

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Learn to use sessionstorage to improve front-end development efficiency Learn to use sessionstorage to improve front-end development efficiency Jan 13, 2024 am 11:56 AM

To master the role of sessionStorage and improve front-end development efficiency, specific code examples are required. With the rapid development of the Internet, the field of front-end development is also changing with each passing day. When doing front-end development, we often need to process large amounts of data and store it in the browser for subsequent use. SessionStorage is a very important front-end development tool that can provide us with temporary local storage solutions and improve development efficiency. This article will introduce the role of sessionStorage,

Subnet mask: role and impact on network communication efficiency Subnet mask: role and impact on network communication efficiency Dec 26, 2023 pm 04:28 PM

The role of subnet mask and its impact on network communication efficiency Introduction: With the popularity of the Internet, network communication has become an indispensable part of modern society. At the same time, the efficiency of network communication has also become one of the focuses of people's attention. In the process of building and managing a network, subnet mask is an important and basic configuration option, which plays a key role in network communication. This article will introduce the role of subnet mask and its impact on network communication efficiency. 1. Definition and function of subnet mask Subnet mask (subnetmask)

See all articles