Math.round vs hack
JavaScript performance comparison
Info
Math.round() has a function call overhead, so using the ~~ hack (truncate towards 0) and adding 0.5 works quicker, but if you want to handle negative numbers too then you have to check whether to add or subtract 0.5 .... and this wipes out the speed advantage. So ~~(0.5+num) is only worth it if you know your numbers always have the same sign...
Preparation code
<script>
var somenum = (Math.random());
var rounded;
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
"proper" rounding |
|
pending… |
Hack rounding |
|
pending… |
Proper hack rounding |
|
pending… |
Hack with bitwise OR |
|
pending… |
Hack with bitwise shift |
|
pending… |
Hack with bitwise OR large num first |
|
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 Tim
- Revision 3: published by Seb Lee-Delisle
- Revision 5: published by Miller Medeiros
- Revision 6: published by Paul King
- Revision 9: published
- Revision 13: published
- Revision 14: published
- Revision 15: published
- Revision 16: published
- Revision 17: published
- Revision 18: published
- Revision 19: published by BrianMB
- Revision 20: published by BrianMB
- Revision 21: published by JeffMo
- Revision 22: published by icrusade
- Revision 23: published
- Revision 24: published
- Revision 25: published by Nico Kruger
- Revision 26: published
- Revision 27: published by Juriy
- Revision 29: published by Hieu Le Trung
- Revision 30: published
- Revision 31: published by george
- Revision 32: published by Andreas Wagner
- Revision 33: published
- Revision 35: published
- Revision 36: published
- Revision 37: published by Hao Wu
- Revision 39: published
- Revision 40: published
- Revision 41: published
- Revision 44: published by twtwt
- Revision 45: published by Christian
- Revision 46: published
- Revision 47: published by Jakob
- Revision 48: published
- Revision 49: published
- Revision 50: published
- Revision 51: published
- Revision 52: published by Terry
- Revision 53: published by Christopher Hall
- Revision 54: published
- Revision 55: published by Ehsan Afzali
- Revision 56: published by Ehsan Afzali
- Revision 57: published
- Revision 58: published
- Revision 59: published by 1Pupik1989
- Revision 60: published
- Revision 61: published
- Revision 62: published by orwellophile
- Revision 63: published by Sergey
- Revision 64: published
- Revision 65: published
1 comment
What if the hacks are inside a function call as well? does that eliminate their advantage