Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 262
Juve Avatar asked Jun 12 '13 09:06

Juve


1 Answers

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).
like image 185
Juve Avatar answered Sep 20 '22 12:09

Juve