Chrome DevTools之Performance
Chrome DevTools中Performance面板可以帮助我们进行性能分析,使我们写出更加精悍的代码。
下面是一段简单的代码。
var _status = {
items:["None", "Java", "Python", "C++", "C", "JavaScript"],
currentFunction: "Java"
}
var currentFn = _status.currentFunction;
var items = _status.items;
function initPage(){
for(var i = 0; i < _status.items; i++){
if(items[i] != currentFn){
console.log(items[i]);
}
}
}

从上面的截图中我们可以看到在点击按钮到函数执行完毕的整个过程中发生的事情。点击button触发click事件,向下执行了InitPage函数。在下面的4个导航栏中,我们可以看到Summary、Bottom-up、Call Tree、Event Log四个导航栏。Summary代表了函数执行过程中,rendering、scripting等各个部分所占总时间的百分比,是一张饼图。Bottom-up是各个部分执行事件的排序。Call Tree是自顶向下的调用栈。这里我们看到initPage函数的时间是0.7ms。
在实际的开发中,我们应尽量if-else选择结构的使用,因为if-else结构效率太低,尤其应该避免大量的if-else结构嵌套,这样使空间复杂度和时间复杂度都增大,在数据量巨大的情况下,这简直就是一场噩梦。下面的代码中我们使用Array.forEach函数来代替if-else选择结构。
function initPage(){
items.forEach(function(el){
if(el != currentFn){
console.log(el);
}
})
}

从上面的截图中我们可以看到initPage函数的执行事件是0.2ms。相比for循环,直接调用forEach函数,执行效率有了提升。
在之前的文章中我们有讲到underscore.js,undescore.js是一个js库,其中封装了很多使用的功能,并支持链式编程。
下面我们用Undescore来改写上面的initPage函数。
function initPage(){
var arr = _.filter(items, el => {return el!= currentFn;});
_.map(arr, el => console.log(el));
}
此处是性能分析 performance3.json
上面通过创建中间变量arr来接受_.filter函数返回的数组。Underscore支持链式编程,通过链式编程我们可以免去此中间变量的创建。
function initPage(){
_.chain(items).
filter( el => {return el != currentFn;}).
map(el => console.log(el));
}
此处是性能分析 performance4.json
因为上面数据量非常小,感觉不是很明显,如果我们修改一下代码,再来看看效率。
function initPage(){
arr.forEach( el => console.log(el));
}
此处是性能分析 performance5.json
让我们再来看看if-else选择结构
function initPage(){
for(var i = 0; i < arr.length; i++){
console.log(i);
}
}
此处是性能分析 performance7.json
当我们用Underscore中链式函数来进行改写时
function initPage(){
_.chain(arr).
map( el => console.log(el));
}
此处是性能分析 performance6.json
总结
上面关于Underscore.js改写的部分,我已经将性能分析文件整体(包括for循环(performance1.json)和forEach函数(performance2.json))压缩上传了。大家可以自己下载,然后分析。关于performance面板使用介绍的大家可以参考这篇文章https://segmentfault.com/a/1190000011516068。
|