Rumah  >  Artikel  >  hujung hadapan web  >  总结一些JavaScript避免使用的函数和语句

总结一些JavaScript避免使用的函数和语句

伊谢尔伦
伊谢尔伦asal
2017-07-26 13:26:061255semak imbas

避免使用eval或者Function构造函数

使用eval或者Function构造函数的代价是非常昂贵的,每次都需要脚本引擎转换源代码到可执行代码。
此外,使用eval处理字符串必须在运行时解释。 

运行缓慢的代码: 

function addMethod(object, property, code) { 
object[property] = new Function(code); 
} 
addMethod(myObj, 'methodName', 'this.localVar=foo');

运行更快的代码: 

function addMethod(object, property, func) { 
object[property] = func; 
} 
addMethod(myObj, 'methodName', function () { 'this.localVar=foo'; });


避免使用with
尽管很方便,with需要附加的查找引用时间,因为它在编译的时候并不知道作用域的上下没。 

运行缓慢的代码: 

with (test.object) { 
foo = 'Value of foo property of object'; 
bar = 'Value of bar property of object'; 
}

运行更快的代码:

var myObj = test.object; 
myObj.foo = 'Value of foo property of object'; 
myObj.bar = 'Value of bar property of object';


不要在性能要求关键的函数中使用try-catch-finally 

try-catch-finally在运行时每次都会在当前作用域创建一个新的变量,用于分配语句执行的异常。
异常处理应该在脚本的高层完成,在异常不是很频繁发生的地方,比如一个循环体的外面。
如果可能,尽量完全避免使用try-catch-finally。 

运行缓慢的代码: 

var object = ['foo', 'bar'], i; 
for (i = 0; i < object.length; i++) { 
try { 
// do something that throws an exception 
} catch (e) { 
// handle exception 
} 
}

运行更快的代码: 

var object = [&#39;foo&#39;, &#39;bar&#39;], i; 
try { 
for (i = 0; i < object.length; i++) { 
// do something 
} 
} catch (e) { 
// handle exception 
}


避免使用全局变量
如果你在一个函数或者其它作用域中使用全局变量,脚本引擎需要遍历整个作用域去查找他们。
全局作用域中的变量在脚本的生命周期里都存在,然后局部范围的会在局部范围失去的时候被销毁。 

运行缓慢的代码: 

var i, 
str = &#39;&#39;; 
function globalScope() { 
for (i=0; i < 100; i++) { 
str += i; // here we reference i and str in global scope which is slow 
} 
} 
globalScope();

运行更快的代码: 

function localScope() { 
var i, 
str = &#39;&#39;; 
for (i=0; i < 100; i++) { 
str += i; // i and str in local scope which is faster 
} 
} 
localScope();


避免在性能要求关键的函数中使用for-in
for-in循环需要脚本引擎建立一张所有可枚举属性的列表,并检查是否与先前的重复。
如果你的for循环作用域中的代码没有修改数组,可以预先计算好数组的长度用于在for循环中迭代数组。 

运行缓慢的代码: 

var sum = 0; 
for (var i in arr) { 
sum += arr[i]; 
}

运行更快的代码: 

var sum = 0; 
for (var i = 0, len = arr.length; i < len; i++) { 
sum += arr[i]; 
}

Atas ialah kandungan terperinci 总结一些JavaScript避免使用的函数和语句. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn