Math.round() vs. Custom Round Function

Benchmark created by Mike on


Description

Bitwise rounding hacks are faster than Math.round() when inserted literally. This will factor in the cost of isolating them to their own functions.

Preparation HTML

<script type="text/javascript">
    var random  = (Math.random()*100) + 0.5,
        rounded = 0,
        customRound = function(n) {
            if(n > 0)
                return (n + 0.5) | 0;
            else {
                n = -n;
                return -(n + 0.5) | 0;
            }
        };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Math.round()
rounded = Math.round(random);
ready
Custom Round Function
rounded = customRound(random);
ready

Revisions

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

  • Revision 1: published by Mike on