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