0

Please refer the Link.

It is suggested that the fastest way to calculate absolute value of a number is by using (relatively difficult) bitwise operator.

I know bitwise operators are faster than division and Multiplication. But are they even faster than + and - operator?

Thanks

Community
  • 1
  • 1
Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137

5 Answers5

16

I'm sure the compiler would be very grateful for your analysis of this situation; it would certainly never have thought of this!

Here's GCC's take on this:

int myabs(int n)
{
  return n < 0 ? -n : n;   // hurray, portable code!
}

Becomes:

mov edx, edi     ;; edx = x
sar edx, 31      ;; edx >>= 31
mov eax, edx
xor eax, edi
sub eax, edx     ;; eax = (x ^ (x >> 31)) - (x >> 31)
ret              ;; return eax
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
5

Measure. In the context you're interested in. I've worked on machines where multiply was faster than shifting, and on machines where it was radically slower. But you can't tell up front. For that matter, what is fastest on the latest Intel may not be fastest on the next one to come out. (The code in the link is the sort of thing you don't want to do. It's not readable, it's not portable, and even on systems where it works, there's a good chance that it is slower than the naïve implementation.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

On just about any platform you'll encounter today, a bitwise operation is exactly as fast as addition and subtraction; the ALU can complete all of these in a single cycle. Some platforms (particularly ARM) can also do a shift in the same cycle as another operation.

Multiplication and division may or may not take longer; that varies from platform to platform.

But note that compilers generally know the fastest way to do simple operations like this, so it's generally not worth trying such micro-optimisations; it's quite easy to accidentally defeat the compiler's optimisation and produce slower code.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

On most modern architectures, bitwise operators like & and | are as fast as arithmetic + and -. In a lot of modern cpu, all these operations take one cpu cycle.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

I have no idea about Javascript, but any C/C++ compiler worth its salt will optimize arithmetic operators to bitwise operations, when possible. I would worry more about keeping your code readable. Sometimes you will see these "tricks" written with bitwise operators, to make it clearer how the trick works.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91