提高 web 应用性能之 JavaScript 性能调优 (2)
 
- UID
- 1066743
|

提高 web 应用性能之 JavaScript 性能调优 (2)
再看如下代码:
清单 5. 慎用 with1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| var myObj = … ..
… ..
function process(){
var doc = document;
var images = doc.getElementsByTagName("img"),
widget = doc.getElementsByTagName("input"),
combination = [];
for(var i = 0; i < images.length; i++){
combination.push(combine(images, widget[2*i]));
}
with (myObj.container) {
property1 = combination[0];
property2 = combination[combination.length-1];
}
}
|
加上“with”关键字,我们让代码更加简洁清晰了,但是这样做性能会受影响。正如之前说的,当我们进入“with”代码块时,“combination”便从原来的层 1 变到了层 2,这样,效率会大打折扣。所以比较一下,还是使用原来的代码:
清单 6. 改进 with1
2
3
4
5
6
7
8
9
10
11
12
13
| var myObj = … ..
… ..
function process(){
var doc = document;
var images = doc.getElementsByTagName("img"),
widget = doc.getElementsByTagName("input"),
combination = [];
for(var i = 0; i < images.length; i++){
combination.push(combine(images, widget[2*i]));
}
myObj.container.property1 = combination[0];
myObj.container.property2 = combination[combination.length-1];
}
|
但是这样并不是最好的方式,JavaScript 有个特点,对于 object 对象来说,其属性访问层级越深,效率越低,比如这里的“myObj”已经访问到了第 3 层,我们可以这样改进一下:
清单 7. 缩小对象访问层级1
2
3
4
5
6
7
8
9
10
11
12
13
14
| var myObj = … ..
… ..
function process(){
var doc = document;
var images = doc.getElementsByTagName("img"),
widget = doc.getElementsByTagName("input"),
combination = [];
for(var i = 0; i < images.length; i++){
combination.push(combine(images, widget[2*i]));
}
var ctn = myObj.container;
ctn.property1 = combination[0];
ctn.property2 = combination[combination.length-1];
}
|
我们用局部变量来代替“myObj”的第 2 层的“container”对象。如果有大量的这种对对象深层属性的访问,可以参照以上方式提高性能。
字符串(String)相关字符串拼接
经常看到这样的代码:
清单 8. 字符串简单拼接
这是我们拼接字符串常用的方式,但是这种方式会有一些临时变量的创建和销毁,影响性能,所以推荐使用如下方式拼接:
清单 9. 字符串数组方式拼接1
2
3
4
| var str_array = [];
str_array.push(“str1”);
str_array.push(“str2”);
str = str_array.join(“”);
|
这里我们利用数组(array)的“join”方法实现字符串的拼接,尤其是程序的老版本的 Internet Explore(IE6)上运行时,会有非常明显的性能上的改进。
当然,最新的浏览器(如火狐 Firefox3+,IE8+ 等等)对字符串的拼接做了优化,我们也可以这样写:
清单 10. 字符串快速拼接1
2
| str +=“str1”
str +=“str2”
|
新的浏览器对“+=”做了优化,性能略快于数组的“join”方法。在不久的将来更新版本浏览器可能对“+”也会做优化,所以那时我们可以直接写:str += “str1” + “str2”。 |
|
|
|
|
|