◆字符串的使用
在IE6和IE7中因字符串级联导致的主要问题是垃圾回收性能,虽然这些问题在IE8中已经得到解决,但如果你的用户大部分仍然在使用IE或IE7,你就得格外注意这个问题了。看一个例子先:
var veryLongMessage = "This is a long string that due to our strict line length limit of" + maxCharsPerLine + " characters per line must be wrapped. " + percentWhoDislike + "% of engineers dislike this rule. The line length limit is for " + " style purposes, but we don't want it to have a performance impact." + " So the question is how should we do the wrapping?";
◆使用连接代替级联:
var veryLongMessage = ["This is a long string that due to our strict line length limit of", maxCharsPerLine, " characters per line must be wrapped. ", percentWhoDislike, "% of engineers dislike this rule. The line length limit is for ", " style purposes, but we don't want it to have a performance impact.", " So the question is how should we do the wrapping?"].join();
与此类似,在条件语句中使用级别也是很低效的,错误的做法:
var fibonacciStr = "First 20 Fibonacci Numbers "; for (var i = 0; i < 20; i++) { fibonacciStr += i + " = " + fibonacci(i) + " "; }
正确的方法:
var strBuilder = ["First 20 fibonacci numbers:"]; for (var i = 0; i < 20; i++) { strBuilder.push(i, " = ", fibonacci(i)," "); } var fibonacciStr = strBuilder.join("");
◆定义类函数
下面的函数是低效的,因为每次构造baz.Bar的实例时,会创建一个新的函数和闭包:
baz.Bar = function () { // constructor body this.foo = function () { // method body }; };
正确的方法是:
baz.Bar = function () { // constructor body this.foo = function () { // method body }; }; baz.Bar = function () { // constructor body }; baz.Bar.prototype.foo = function () { // method body };
使用这个方法时,无论baz.Bar构造了多少个实例,都只会为foo创建一个函数,而且不会创建闭包。
◆初始化实例变量
使用实例变量值类型初始值初始化实例变量声明,如数值、布尔值、空值、未定义或字符串,这样可以避免每次调用构造器时运行不必要的初始化代码。还是来看一个例子:
foo.Bar = function () { this.prop1_ = 4; this.prop2_ = true; this.prop3_ = []; this.prop4_ = "blah"; };
可以使用:
foo.Bar = function () { this.prop3_ = []; }; foo.Bar.prototype.prop1_ = 4; foo.Bar.prototype.prop2_ = true; foo.Bar.prototype.prop4_ = "blah";
进行代替。
◆避免使用with
避免在代码中使用with,它会影响到性能,因为它修改了范围链,因此需要花费更多时间到其它范围去查找。
◆避免浏览器内存泄漏
对于Web应用程序而言,内存泄漏是很常见的事情,可能因此导致巨大的性能问题。因为浏览器的内存使用在增长,你的Web应用程序和其它程序就会变慢,最常见的内存泄漏是在JavaScript引擎和浏览器C++对象实现的DOM之间形成了循环引用,如在JavaScript引擎和IE浏览器的COM基础结构之间,以及JavaScript引擎和Firefox XPCOM基础结构之间。