今天针对不同的数组判定方式在chrome上做了一个效率的对比,结果如下:
其代码如下:
var ret;
var o = [1,2,3];
var toStr = {}.toString;
var array = {};
array["[object Array]"] = "array";
console.log("各种判断是否数组的速度比较!")
console.log("方法一:Array.isArray(o)");
console.time("first");
for (var i=0;i<10000;i++){
ret = Array.isArray(o);
}
console.timeEnd("first");
console.log(ret);
console.log("方法二:o instanceof Array");
console.time("second");
for (var i=0;i<10000;i++){
ret = o instanceof Array;
}
console.timeEnd("second");
console.log(ret);
console.log("方法三:o.constructor == Array");
console.time("thirth");
for (var i=0;i<10000;i++){
ret = o.constructor == Array;
}
console.timeEnd("thirth");
console.log(ret);
console.log("方法四:array[toStr.call(o)] == 'array'");
console.time("forth");
for (var i=0;i<10000;i++){
ret = array[toStr.call(o)] == "array";
}
console.timeEnd("forth");
console.log(ret);