Due to the number of previous text exceeded the limit so js code optimization part is written here
Previous address: juejin.cn/post/688341…
Section TS: juejin.cn/post/688342…
The third part :JS performance optimization
Introduction to code optimization
- How do you accurately test JavaScript performance — essentially mathematical statistics and analysis with execution samples
- This can be done using jsbench. Me /
20: Be careful with global variables
-
Why should it be used sparingly
-
Global variable definitions have a global execution context and are at the top of any scope chain
-
The global execution context remains in the context execution stack until the program exits
-
If a variable with the same name appears in a local scope, it will be obscured or polluted
Var I, STR = ""; for (i = 0; i < 1000; i++) { str += i; } // for (let I = 0; i < 1000; i++) { let str = ""; str += i; }Copy the code
Twenty-one: Cache global variables
- Caching global variables locally that are unavoidable in use (for example, document is required to find Dom elements)
Function getBtn1() {let oBtn1 = document.getelementById ("btn1"); let oBtn3 = document.getElementById("btn3"); let oBtn5 = document.getElementById("btn5"); let oBtn7 = document.getElementById("btn7"); let oBtn9 = document.getElementById("btn9"); } function getBtn2() {let obj = document; Let oBtn1 = obj.getElementById("btn1"); let oBtn3 = obj.getElementById("btn3"); let oBtn5 = obj.getElementById("btn5"); let oBtn7 = obj.getElementById("btn7"); let oBtn9 = obj.getElementById("btn9"); }Copy the code
Add additional methods through prototype objects
-
Add by prototype
-
Methods needed to add an instance object to a prototype object
// No prototype object is used; var fn1 = function () { this.foo = function () { console.log(11111); }; }; let f1 = new fn1();
Var fn2 = function () {}; fn2.prototype.foo = function () { console.log(11111); }; let f2 = new fn2();
Avoid the trap of closures
Function foo1() {var name = "XJQ "; return function fn() { console.log(name); }; } foo1()(); Function foo2() {var el = document.getelementById (" BTN "); el.onclick = function () { console.log(el.id); }; // demo // optimize -- fix memory leak -- free memory space el = null; } foo2();Copy the code
Twenty-four: Avoid using attribute access methods
-
Object orientation in JavaScript
-
JS properties do not require access methods for properties; all properties are externally visible
-
Using attribute access methods adds a layer of redefinition without access control
Function Person1() {this.name = “icoder”; this.age = 18; this.getAge = function () { return this.age; }; } const p1 = new Person1(); const a = p1.getAge();
Function Person2() {this.name = “icoder”; this.age = 18; } const p2 = new Person2(); const b = p2.age;
Twenty-five: Cycle optimization
var aBtns = document.getElementsByClassName("btn"); for (let i = 0; i < aBtns.length; i++) { console.log(i); } for (let I = 0, len = abtns.length; i < len; i++) { console.log(i); }Copy the code
Choose the optimal cycle scheme
-
foreach
-
for
-
for.. in
Var arrList = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9); arrlist.forEach(function (item) { console.log(item); });
for (let i = 0, len = arrlist.length; i < len; i++) {
console.log(arrlist[i]);
}
for (let i in arrlist) {
console.log(arrlist[i]);
}
Twenty-seven: Document fragmentation optimization node
-
Node addition optimization
-
The addition of nodes inevitably involves backflow and redrawing
for (var i = 0; i < 10; i++) {
var oP = document.createElement(“p”);
oP.innerHTML = i;
document.body.appendChild(oP);
}/ / optimize / / create a container const fragEle = document. CreateDocumentFragment (); for (var i = 0; i < 10; i++) { var oP = document.createElement(“p”); oP.innerHTML = i; fragEle.appendChild(oP); } document.body.appendChild(fragEle);
Twenty-eight: Clone optimization node operation
For (var I = 0; i < 10; i++) { var oP = document.createElement("p"); oP.innerHTML = i; document.body.appendChild(oP); Var oldP = document.getelementbyId ("box1"); for (var i = 0; i < 10; i++) { var newP = oldP.cloneNode(false); newP.innerHTML = i; document.body.appendChild(newP); }Copy the code
29: Replace the new Object directly
Var a = [1, 2, 3]; //new Object var b = new Array(3); b[0] = 1; b[1] = 2; b[2] = 3;Copy the code
Thirty: Reduce hierarchy
Function doSomething(part, chapter) {const parts = ["ES2016", "Vue", "React", "Node"]; If (part) {if (parts.includes(part)) {console.log(" no this course "); If (chapter > 5) {console.log(" you are not VIP "); }}} else {console.log(" no output course "); } } doSomething("ES2016", 6); Function doSomething1(part, chapter) {const parts = ["ES2016", "Vue", "React", "Node"]; if (! Parts) {console.log(" no course output "); return; } if (! parts.includes(part)) return; Console. log(" there is no course "); If (chapter > 5) {console.log(" you are not VIP "); } } doSomething1("ES2016", 6);Copy the code
Thirty-one: Reduce the scope chain lookup level
-
The following example is optimized but there is space for time
var name = “xjq”; function foo() { name = “xjq666”; Function bar() {var age = 38; console.log(age); console.log(name); Name} bar(); } foo();
Var name = “XJQ “; function foo() { var name = “xjq666”; Function bar() {var age = 38; console.log(age); console.log(name); // look up bar, name} bar(); } foo();
Thirty-two: Reduce the number of data reads
-
Fast data access in the stack area
-
Data access in the heap is slow because you need to find locations based on reference relationships
var oBox = document.getElementById(“skip”);
function hasEle(ele, cls) {
return ele.className == cls;
}Function hasEle(ele, CLS) {var clsname = ele.classname; return clsname == cls; } console.log(hasEle(oBox, “skip”));
33: Literals in constructional expressions
Let test = () => {let obj = new Object(); let obj = new Object(); obj.name = "xjq"; obj.age = 22; obj.slogan = "123456"; return obj; }; let test = () => { let obj = { name: "xjq", age: 22, slogan: "123456", }; return obj; }; // test(); console.log(test()); Var str1 = "XJQ "; var str2 = new String("xjq");Copy the code
Thirty-four: Reduce activity in circulatory body
-
Unnecessary code can be extracted for execution outside of circulation (frequently used and constant values)
var test = () => { var i; Var arr = [” XJQ “, 22, “male “]; for (i = 0; i < arr.length; i++) { console.log(arr[i]); }};
Var test = () => {var I; Var arr = [” XJQ “, 22, “male “]; var len = arr.length; for (i = 0; i < len; i++) { console.log(arr[i]); }};
Var test = () => {var arr = [” XJQ “, 22, “male “]; var len = arr.length; while (len–) { console.log(arr[len]); }};
35: Reduce declarations and statements
<div id="box" style="width: 100px; height: 100px"></div> var oBox = document.getElementById("box"); var test = (ele) => { let w = ele.offsetWidth; let h = ele.offsetHeight; return w + h; }; Var test = (ele) => {return ele.offsetwidth + ele.offsetheight; }; test(oBox); var test = () => { var name = "xjq"; var age = 22; var slogan = "123456"; return name + age + slogan; }; // Optimize var test = () => {var name = "XJQ ", age = 22, slogan = "123456"; return name + age + slogan; }; test();Copy the code
Thirty-six: Use event binding
<ul id="ul">
<li>x</li>
<li>j</li>
<li>q</li>
</ul>
var list = document.querySelectorAll("li");
function showTxt(ev) {
console.log(ev.target.innerHTML);
}
for (let item of list) {
item.onclick = showTxt;
}
var oUI = document.getElementById("ul");
oUI.addEventListener("click", showTxt, true);
Copy the code