-2

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

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
user2918741
  • 87
  • 1
  • 10

1 Answers1

0

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
  • Bitwise (x ^ (x >> 31)) - (x >> 31) is mostly fastest in Chrome and Operah
  • Ternary (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:

  • time wasted on browser-profiling (reliability while loading the page) or browser-detection (well, reliability in general..)
  • extra bandwidth for larger javascript
  • (usually) larger memory-footprint (because on the fly generated functions are often slower then static defined functions (that are given the proper indentifier)

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!

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80