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!