quick-commaify-number

JavaScript performance comparison

Test case created by henrahmagix

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var longNumber = 123456789;
    var addCommasStringConcat = function(str) {
        var amount = str.toString().split("").reverse();
   
        var output = '';
        for (var i = 0, l = amount.length - 1; i <= l; i++) {
            output = amount[i] + output;
            if ((i+1) % 3 === 0 && l !== i)
                output = ',' + output;
        }
        return output;
    };
    var addCommasArrayJoin = function(str) {
        var amount = str.toString().split("").reverse();
   
        var output = [];
        for (var i = 0, l = amount.length - 1; i <= l; i++) {
            output.push(amount[i]);
            if ((i+1) % 3 === 0 && l !== i) {
                output.push(',');
            }
        }
        return output.reverse().join('');
    };
    var addCommasArrayJoinUnshift = function(str) {
        var amount = str.toString().split("").reverse();
   
        var output = [];
        for (var i = 0, l = amount.length - 1; i <= l; i++) {
            output.unshift(amount[i]);
            if ((i+1) % 3 === 0 && l !== i) {
                output.unshift(',');
            }
        }
        return output.join('');
    };
    var addCommasArrayJoinMap = function(str) {
        var amount = str.toString().split("").reverse();
        var l = amount.length;
   
        var output = amount.map(function (n, i) {
            if ((i + 1) % 3 === 0 && l !== i) {
                return ',' + n;
            }
            return n;
        });
        return output.reverse().join('');
    };
   
};
</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
String Concat
addCommasStringConcat(longNumber)
pending…
Array Join
addCommasArrayJoin(longNumber)
pending…
Array Join Unshift
addCommasArrayJoinUnshift(longNumber)
pending…
Array Join Map
addCommasArrayJoinMap(longNumber)
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