Editing Math.round vs hack (utility function) This edit will create a new revision. Your details (optional) Name Email (won’t be displayed; might be used for Gravatar) URL Test case details Title * Published (uncheck if you want to fiddle around before making the page public) Description (in case you feel further explanation is needed)(Markdown syntax is allowed) 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... This compares Math.round() with the hack methods in http://jsperf.com/math-round-vs-hack/3 wrapped in a utility function. Are you a spammer? (just answer the question) Preparation code Preparation code HTML (this will be inserted in the <body> of a valid HTML5 document in standards mode) (useful when testing DOM operations or including libraries) <script> var somenum = -500 + (Math.random() * 1000); var rounded; function hack_rounding_utility(value) { return ~~ (0.5 + value); } function proper_hack_rounding_utility(value) { return ~~ (value + (value > 0 ? .5 : -.5)); } function hack_rounding_bitwise_or(value) { return (0.5 + value) | 0; } function hack_rounding_bitwise_shift(value) { return (0.5 + value) << 0; } </script> Include JavaScript libraries as follows: <script src="//cdn.ext/library.js"></script> Define setup for all tests (variables, functions, arrays or other objects that will be used in the tests) (runs before each clocked test loop, outside of the timed code region) (e.g. define local test variables, reset global variables, clear canvas, etc.) (see FAQ) Define teardown for all tests (runs after each clocked test loop, outside of the timed code region) (see FAQ) Code snippets to compare Test 1 Title Async (check if this is an asynchronous test) Code rounded = Math.round(somenum); Test 2 Title Async (check if this is an asynchronous test) Code rounded = ~~ (0.5 + somenum); Test 3 Title Async (check if this is an asynchronous test) Code rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5)); Test 4 Title Async (check if this is an asynchronous test) Code rounded = (0.5 + somenum) | 0; Test 5 Title Async (check if this is an asynchronous test) Code rounded = (0.5 + somenum) << 0; Test 6 Title Async (check if this is an asynchronous test) Code rounded = hack_rounding_utility(somenum); Test 7 Title Async (check if this is an asynchronous test) Code rounded = proper_hack_rounding_utility(somenum); Test 8 Title Async (check if this is an asynchronous test) Code rounded = hack_rounding_bitwise_or(somenum); Test 9 Title Async (check if this is an asynchronous test) Code rounded = hack_rounding_bitwise_shift(somenum);