Summary of improving JS execution 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();
functions The default value of the parameter
Function doSomething(arg1){ Arg1 = arg1 || 10; // 如果 arg1为设置那么 Arg1=10 }
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]
3. Rounding to decimal places
var num =2.443242342; num = num.toFixed(4); // 保留四位小数位 2.4432
4. Floating point number problem
0.1 + 0.2 === 0.3 // is false 9007199254740992 + 1 // = 9007199254740992 9007199254740992 + 2 // = 9007199254740994
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)) { // 执行代码 } }
6. Comma operator
var a = 0; var b = ( a++, 99 ); console.log(a); // a 为 1 console.log(b); // b 为 99
7. Calculate or query cache variables
Developers can cache DOM elements when using jQuery selectorsvar 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 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]
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 */
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);
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]; }
var sum = 0; for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i]; }
for (var i = 0; i < arrayNumbers.length; i++)
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('doSomethingPeriodically()', 1000); setTimeOut('doSomethingAfterFiveSeconds()', 5000);
setInterval(doSomethingPeriodically, 1000); setTimeOut(doSomethingAfterFiveSeconds, 5000);
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"
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 ; // []
18. An HTML escaper function
function escapeHTML(text) { var replacements= {"<": "<", ">": ">","&": "&", "\"": """}; return text.replace(/[<>&"]/g, function(character) { return replacements[character]; }); }
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) { // 获取错误,并执行代码 } }
应该这样使用:
var object = ['foo', 'bar'], i; try { for (i = 0, len = object.length; i <len; i++) { // 执行代码,如果出错将被捕获 } } catch (e) { // 获取错误,并执行代码 }
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();
此外,通常你应该完全避免同步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); } }
keepAlive()方法应该添加在WebSocket链接方法onOpen()的末端,cancelKeepAlive()方法放在onClose()方法下面。
22.记住,最原始的操作要比函数调用快
对于简单的任务,最好使用基本操作方式来实现,而不是使用函数调用实现。
例如
var min = Math.min(a,b); A.push(v);
基本操作方式:
var min = a < b ? a b; A[A.length] = v;
23.编码时注意代码的美观、可读
JavaScript是一门非常好的语言,尤其对于前端工程师来说,JavaScript执行效率也非常重要。
我们在编写JavaScript程序时注意一些小细节,掌握一些常用的实用小技巧往往会使程序更简捷,程序执行效率更高
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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.

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

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

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

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,

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)
