JavaScript性能陷阱
JavaScript陷阱太多,因此我们得步步为营,以下是一些常见的影响性能的陷阱和处理办法总结,希望对你有所帮助。
1.避免使用eval或者Function构造函数
使用eval或者Function构造函数的代价是非常昂贵的,每次都需要脚本引擎转换源代码到可执行代码。
此外,使用eval处理字符串必须在运行时解释。
运行缓慢的代码:
1 2 3 4 | function addMethod(object, property, code) { object[property] = new Function(code); } addMethod(myObj, 'methodName', 'this.localVar=foo'); |
运行更快的代码:
1 2 3 4 | function addMethod(object, property, func) { object[property] = func; } addMethod(myObj, 'methodName', function () { 'this.localVar=foo'; }); |
2.避免使用with
尽管很方便,with需要附加的查找引用时间,因为它在编译的时候并不知道作用域的上下没。
运行缓慢的代码:
1 2 3 4 | with (test.object) { foo = 'Value of foo property of object'; bar = 'Value of bar property of object'; } |
运行更快的代码:
1 2 3 | var myObj = test.object; myObj.foo = 'Value of foo property of object'; myObj.bar = 'Value of bar property of object'; |
3.不要在性能要求关键的函数中使用try-catch-finally
try-catch-finally在运行时每次都会在当前作用域创建一个新的变量,用于分配语句执行的异常。
异常处理应该在脚本的高层完成,在异常不是很频繁发生的地方,比如一个循环体的外面。
如果可能,尽量完全避免使用try-catch-finally。
运行缓慢的代码:
1 2 3 4 5 6 7 8 | var object = ['foo', 'bar'], i; for (i = 0; i < object.length; i++) { try { // do something that throws an exception } catch (e) { // handle exception } } |
运行更快的代码:
1 2 3 4 5 6 7 8 | var object = ['foo', 'bar'], i; try { for (i = 0; i < object.length; i++) { // do something } } catch (e) { // handle exception } |

