Byte Formatting

JavaScript performance comparison

Revision 4 of this test case created by Mr. X

Info

Simple test that compares speed of two methods to format bytes to human-readable format.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var results = [
        10240,
        10485760,
        10737418240,
        10995116277760,
        11258999068426240
        ],
        sizes = [
                "B",
                "kB",
                "MB",
                "GB",
                "TB"
                ],
        strings = {
        "na": "n/a"
    },
        undefined;
       
   
    function formatBytesNew(bytes) {
        if (bytes === undefined || bytes === '0' || isNaN(bytes)) {
                return strings.na;
        }
        // 6.931471805599453 = Math.log(1024);
        var i = ~~ (Math.log(bytes) / 6.931471805599453);
        return ~~ (0.5 + bytes / results[i]) / 10 + ' ' + sizes[i];
    }
   
    function formatBytesOld(bytes) {
        if (bytes === undefined || bytes === '0' || isNaN(bytes)) {
                return strings.na;
        }
        // 6.931471805599453 = Math.log(1024);
        var i = ~~ (Math.log(bytes) / 6.931471805599453);
        return Math.round(bytes / results[i]) / 10 + ' ' + sizes[i];
    }
};
</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
Old Version Small
formatBytesOld(66666);
pending…
Optimized Small
formatBytesNew(66666);
pending…
Old Large
formatBytesOld(66666666666);
pending…
Optimized Large
formatBytesNew(66666666666);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment