Home >Web Front-end >JS Tutorial >4 methods and efficiency comparison of JavaScript to determine whether it is a number_javascript skills
Today I did an efficiency comparison on Chrome for different numerical determination methods. The results are as follows:
Note: Regular expressions can only be used to determine whether the content in a string is a pure numeric value, but cannot be used to determine whether it is a numeric object. Put here only for comparison.
The code is as follows:
var ret; var o = 1; var pattern = /^(-?\d*.?\d*)$/; var toStr = {}.toString; var array = {}; array["[object Number]"] = "number"; console.log("各种判断是否数值的速度比较!") console.log("方法一:pattern.test(o)"); console.time("first"); for (var i=0;i<10000;i++){ ret = pattern.test(o); } console.timeEnd("first"); console.log(ret); console.log("方法二:o instanceof Number"); console.time("second"); for (var i=0;i<10000;i++){ ret = o instanceof Number; } console.timeEnd("second"); console.log(ret); console.log("方法三:o.constructor == Number"); 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)] == 'number'"); console.time("forth"); for (var i=0;i<10000;i++){ ret = array[toStr.call(o)] == "number"; } console.timeEnd("forth"); console.log(ret);