Fast and save way to remove the sign of a singed number in JavaScript

Juve picture Juve · Jun 12, 2013 · Viewed 7.7k times · Source

I want to remove the sign of a Number in JavaScript. Here are the test cases that I already examined at jsperf (http://jsperf.com/remove-sign-from-number)

if(n < 0) n *= -1;

if(n < 0) n = -n;

n = Math.abs(n)

(n < 0) && (n *= -1)

(n < 0) && (n = -n)

n = Math.sqrt(n*n)

According to these tests: if(n < 0) n *= -1 seems to be a good solution.

Do you know of any better, save, and more efficient way to do that?

Edit 1: Added Nikhil's Math.sqrt case, but sqrt is usually quite slow in most systems.

Edit 2: Jan's proposal for bitwise ops may be faster in some cases but will also remove fractional digits, and thus will not work for me.

Answer

Juve picture Juve · Jun 17, 2013

Since no better answer appeared I will summarize the findings in this answer myself.

  1. if(n < 0) n *= -1 Is currently the best choice. It performs reasonably well on most platforms and is very readable. It also preserves the decimal fractions.
  2. Other variants, such as n = Math.abs(n), might be faster on other platforms. But the gain is usually only a few percentages. You may consider detecting the browser/platform upfront and building platform-depended code that uses one or the other variant. This can give you the best performance on each platform but introduces a lot of overhead.
  3. Be careful when considering bitwise operators, they might be faster on some platforms but can change the semantics of your program (removing decimal fractions).