Math.round vs bitwise shift
JavaScript performance comparison
Info
Compare various ways of rounding.
Preparation code
<script>
Benchmark.prototype.setup = function() {
var somenum = -500 + (Math.random() * 1000), rounded = 1000;
};
Benchmark.prototype.teardown = function() {
var round, or, not, left, result;
round = Math.round(somenum);
or = (somenum + (somenum > 0 ? .5 : -.5)) | 0;
not = ~~ (somenum + (somenum > 0 ? .5 : -.5));
left = (somenum + (somenum > 0 ? .5 : -.5)) << 0;
if(round == or && or == not && not == left) result = ('all values = '+round+' from: '+somenum);
else result = (['values do not match!','round:'+round,'or'+or,'not'+not,'left'+left, 'from:'+somenum].join('; '));
if(window.console && console.log) console.log(result);
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Math.round |
|
pending… |
bitwise NOT |
|
pending… |
bitwise OR |
|
pending… |
bitwise left shift |
|
pending… |
Math.round 2 |
|
pending… |
bitwise NOT 2 |
|
pending… |
bitwise OR 2 |
|
pending… |
bitwise left shift 2 |
|
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:
- Revision 1: published by Jim Montgomery
- Revision 2: published
0 comments