今天針對不同的數組判定方式在chrome上做了一個效率的對比,結果如下:
其代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 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);