其他分享
首页 > 其他分享> > 代码优化介绍

代码优化介绍

作者:互联网

1、如何精准测试JavaScript性能

(1)本质上就是采用大量的执行样本进行数学统计和分析

(2)使用基于Benchmark.js的https://jsperf.com完成

2、Jsperf使用流程

(1)使用GitHub账号登录

(2)填写个人信息(非必填)

(3)填写详细的测试用例信息(title、slug)

(4)填写准备代码(DOM操作时经常使用)

(5)填写必要有setup与teardown代码

(6)填写测试代码片段

3、慎用全局变量

(1)全局变量定义在全局执行上下文,是所有作用域的顶端

(2)全局执行上下文一直存在于上下文执行栈,直到程序退出

(3)如果某个局部作用域出现了同名变量则会遮蔽或污染全局

4、通过原型对象添加附加方法

var fn1 = function() {
    this.foo = function(){
        console.log('this')
    }
}
let f1 = fn1();
var fn2 = function(){
    fn2.prototype = function(){
        console.log('prototype');
    }
}
let f2 = fn2();
View Code

5、避开闭包陷阱

(1)闭包是一种强大的语法

(2)闭包使用不当很容易出现内存泄露

(3)不要为了闭包而闭包

function test(func) {
    console.log(func());
}

test(function(){
    var name = 'zs';
    return name;
})
function test2(){
    var name = 'lg';
    return name;
}
test(test2)
View Code

6、避免属性方法的使用

(1)JS不需要属性的访问方法,所有属性都是外部可见的

(2)使用属性访问方法只会增加一层重定义,没有访问的控制力

function Person(){
    this.name = 'lisa';
    this.age = 18;
    this.getAge = function(){
        return this.age
    }
}

const p1 = new Person();
const a = p1.getAge();

function Person2(){
    this.name = 'la';
    this.age = 18;
}
const p2 = new Person2();
const b = p2.age;
View Code

 7、For循环优化

var arrList = [];
arrList[10000] = 'icoder';
for (let i = 0; i < arrList.length; i++) {
    console.log(i)
}

for (let i = arrList.length; i; i--) {
    console.log(i)
}
View Code

8、选择最优的循环方法

var arrList  = new Array(1,2,3,4,5);
for (let i = arrList.length; i; i--) {
    console.log(arrList[i]); 
}
arrList.forEach(element => {
    console.log(element);
});
for (const item in arrList) {
    console.log(arrList[item]);
}
View Code

foreach最优,forin最差

9、节点添加优化

for (let i = 0; i < 10; i++) {
            var p = document.createElement('p');
            p.innerHTML = i;
            document.body.appendChild(p);
        }
        const fragEle = document.createDocumentFragment();
        for (let i = 0; i < 10; i++) {
            var p = document.createElement('p');
            p.innerHTML = i;
            fragEle.appendChild(p);
        }
        document.body.appendChild(fragEle);
View Code

10、克隆优化节点操作

var oldP = document.getElementById('box1');
        for (let i = 0; i < 10; i++) {
            var newP = oldP.cloneNode(true);
            newP.innerHtml = i;
            document.body.appendChild(newP);
        }
View Code

11、直接量替换Object操作

 

var array = new Array();
        array[0] = 1;
        array[1] = 1;
        array[2] = 1;
        var array1 = [1, 2, 3];
View Code

 

标签:function,console,log,arrList,代码优化,let,介绍,var
来源: https://www.cnblogs.com/phantomyy/p/14366093.html