-4

I'm trying to maximize my FLOPS in NodeJS, so I want to add using bitwise operations.

So:

var a = 6, b = 12;
a + b

Instead:

var add = function (a, b) {
    var carry, result, shiftedcarry;

    carry = a & b,
    result = a ^ b;

    while (carry !== 0) {
        shiftedcarry = carry << 1;
        carry = result & shiftedcarry;
        result ^= shiftedcarry;
    }

    return result;
}

add(a, b);

However, I found SO answers that said bitwise operations are slower in Javascript due to casting. Is there anyway to bypass this problem (like with a V8 extension or something)?

The reason I'm so focused on increasing my FLOPS is because I'm thinking of running a NodeJS experiment on a supercomputer.

  • 2
    If you're worried about this, you probably shouldn't be writing this in JavaScript. V8 is fast, but very far from optimal. – Brigand Jul 18 '14 at 01:15
  • 1
    That's what V8's JIT is for. In most cases you don't need to 'optimize' but rather you need to avoid deoptimization. Here's a link that can get you started: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers – generalhenry Jul 18 '14 at 01:20
  • 1
    I believe this is the case of premature optimization. – PM 77-1 Jul 18 '14 at 01:21

1 Answers1

2

V8 is a pretty good JIT. After enough iterations it will optimize the simple a + b better than you can.

I made a jspref test to demonstrate: http://jsperf.com/add-optimization

If you want to really dive in you can poke at V8's output How can I see the machine code generated by v8?

Community
  • 1
  • 1
generalhenry
  • 17,227
  • 4
  • 48
  • 63