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();"||" can also be used to set
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 // = 90071992547409940.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)) { // 执行代码 } }
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]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 */
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]; }This will be more efficient Good:
var sum = 0; for (var i = 0, len = arrayNumbers.length; i 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: <p style="text-align: left;"></p><pre class="brush:php;toolbar:false">for (var i = 0; i Why ? The array length, arrayynNumbers, is recalculated on each loop iteration. <p style="text-align: left;"></p><p style="text-align: left;"><span style="color: #ff0000">14. Do not pass strings to the setTimeout() and setInterval() methods <strong></strong></span></p>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: <p style="text-align: left;"></p><pre class="brush:php;toolbar:false">setInterval('doSomethingPeriodically()', 1000); setTimeOut('doSomethingAfterFiveSeconds()', 5000);Instead, it should be used like this:
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 <p style="text-align: left;"><span style="color: #ff0000">17.<strong>Create An object<a href="http://www.php.cn/code/8128.html" target="_blank"> whose properties are a given object</a></strong></span></p>You can write such a function to create an object whose properties are a given object, such as Like this: <p style="text-align: left;"></p><pre class="brush:php;toolbar:false">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><p style="text-align: left;">应该这样使用:</p> <pre class="brush:php;toolbar:false">var object = ['foo', 'bar'], i; try { for (i = 0, len = object.length; i <len catch><p style="text-align: left;"><span style="color: #ff0000"><strong>20.给XMLHttpRequests设置timeouts</strong></span></p> <p style="text-align: left;">如果一个XHR需要花费太长时间,你可以终止链接(例如网络问题),通过给XHR使用setTimeout()解决。</p> <pre class="brush:php;toolbar:false">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 <p style="text-align: left;"><span style="color: #ff0000"><strong>23.编码时注意代码的美观、可读</strong></span></p><p style="text-align: left;">JavaScript是一门非常好的语言,尤其对于前端工程师来说,JavaScript执行效率也非常重要。</p><p style="text-align: left;">我们在编写JavaScript程序时注意一些小细节,掌握一些常用的实用小技巧往往会使程序更简捷,程序执行效率更高</p><p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p><p>推荐阅读:</p><p><a href="http://www.php.cn/js-tutorial-393821.html" target="_blank">JS中时间单位比较的方法</a><br></p><p><a href="http://www.php.cn/js-tutorial-393817.html" target="_blank">JS操作JSON详细介绍</a><br></p>
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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools