I am using Math.abs for my 1000 points as below
Math.abs(a - b) < tolerance;
My profiler shows that Math.abs uses 62 ms, I need to optimize it, so tried this
((a-b) < 0 ?-(a-b) : a-b) < tolerance;
I want to know which is better and fast
I am using Math.abs for my 1000 points as below
Math.abs(a - b) < tolerance;
My profiler shows that Math.abs uses 62 ms, I need to optimize it, so tried this
((a-b) < 0 ?-(a-b) : a-b) < tolerance;
I want to know which is better and fast
It highly depends on the browser (and version) used as you can see in this jsperf and is discussed in related question on SO:
Anno 2013 one could state that:
Math.abs()
is mostly fastest in IE, FireFox and Safari (x ^ (x >> 31)) - (x >> 31)
is mostly fastest in Chrome and Operah (x < 0 ? -x : x)
was only the fastest in FireFox 3.x and 4 era.You could provide a dynamic function-loader to initiate the optimal function (based on live in-browser speed-profiling or browser-detection), containing the fastest routine for that browser.
Naturally this comes at a couple of costs:
So in general I'd prefer:
Mah.abs()
(since that is often the smallest and clearly indicates intent).
Followed by the ternary (often coupled with the comma-operator by which I can perform more logic with just one test, this can be both faster/shorter and even require less programming-logic).
Finally the bitwise variant reveals the least intent, doesn't offer some of the above ternary-advantages AND only works reliable if you have no more than 32 bits..
Hope this helps!