converting numbers regex vs javascript funcs

JavaScript performance comparison

Test case created by Russell Dempsey

Info

tests whether value is a number or not and assigns it appropriately.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var numbersToTest = [1, '1', 1.1, '1.1', 2.4785, '2.4785', 576.4, '576.4', '', -12.34, '-12.34', NaN, Infinity, undefined, 'not a number'];
   
   
    var someArray = [];
   
    function nanny(){
       
    }
};

Benchmark.prototype.teardown = function() {
    someArray = [];
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
regex test
for (var num = 0; num < numbersToTest.length; num++)
{
            var value = numbersToTest[num];
            if (/^-?\d+(\.\d*)?$/.test(value))
                value = parseFloat(value);
            someArray.push(value);
}
pending…
isFinite()
for (var num = 0; num < numbersToTest.length; num++)
{
            var value = numbersToTest[num];
            var temp = parseFloat(value);
            if (isFinite(temp))
                value = temp;
            someArray.push(value);
}
pending…
typeof !== 'NaN'
for (var num = 0; num < numbersToTest.length; num++)
{
            var value = numbersToTest[num];
            if (typeof parseFloat(value).toString() !== 'NaN' )
                value = parseFloat(value);
            someArray.push(value);
}
pending…
convert and back
for (var num = 0; num < numbersToTest.length; num++)
{
            var value = numbersToTest[num];
            var temp = parseFloat(value);
            if (temp.toString() == value )
                value = temp;
            someArray.push(value);
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment