Math.round vs hack
JavaScript performance comparison
Info
Test of different ways of rounding numbers, results vary a lot according to browsers and JS engines are getting smarter each day, so it is usually a better approach to don't try to be smarter than the engines and use the native feature (in this case, Math.round) since there is a bigger chance of performance improvements in the future and especially because bitwise operations reduces code readability.
Preparation code
<script>
var somenum = -500 + (Math.random() * 1000);
var rounded;
var round = Math.round; //cached
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
"proper" rounding |
|
pending… |
Bitwise NOT |
|
pending… |
Proper hack rounding |
|
pending… |
Bitwise OR |
|
pending… |
Bit shift left |
|
pending… |
Native casting |
|
pending… |
Bitwise AND |
|
pending… |
Bitshift right |
|
pending… |
Bitshift right (0 fill) |
|
pending… |
Bitwise XOR |
|
pending… |
Cached Reference |
|
pending… |
Math.floor |
|
pending… |
Math.ceil |
|
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
0 comments