今天針對不同的陣列判定方式在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);