One would think that modern JIT compiler implementations of JS would

make this whole discussion moot...

On Fri, Sep 4, 2009 at 4:01 PM,

aseem.kishore@...<

aseem.kishore@...> wrote:

>

>

> --- In jslint_com@yahoogroups.com, Stefan Weiss <weiss@...> wrote:

>

>>

>> On 04/09/09 18:10, aseem.kishore@... wrote:

>> > For curiosity's sake, I did some testing between bit-shifting and

>> > regular math, and it seems bit-shifting is in fact faster for the

>> > cases I use.

>> >

>> > Using these two functions, with i going from 0 to 50000:

>> >

>> > function pow2BitShifting(i) {

>> > var x = 1 << (i % 30);

>> > }

>> >

>> > function pow2RegularMath(i) {

>> > var x = Math.pow(2, (i % 30));

>> > }

>>

>> That's not really a fair comparison. The second function has to do a

>> lookup for 'Math', find its 'pow' property, and execute a method call to

>> Math.pow.

>>

>> So yes, in this case, bit shifting is faster than a call to Math.pow

>> with base 2, but that doesn't prove that the bit operations themselves

>> are handled efficiently in JS.

>>

>>

>> cheers,

>> stefan

>>

>

> Fair point. Since that's my use case, it's a valid comparison for my

> scenario (even if I cache a local reference to Math.pow first, the numbers

> are almost identical, so apparently the bottleneck isn't the lookups).

>

> But to make a more fair comparison for the purposes of the underlying

> question, I changed the test to this:

>

> function times2BitShifting(i) {

> var x = i << 1;

> }

>

> function times2RegularMath(i) {

> var x = 2 * i;

> }

>

> Again, i goes from 0 to 50000. Across all browsers, the two take essentially

> the same amount of time. I sometimes just get a 1 ms difference in favor of

> bit-shifting.

>

> Doubling w/ bit-shifting: 31

> Doubling w/ regular math: 32

>

> So is this a fair enough comparison? Using bitwise operators seems to have

> no performance penalty, and in cases where it's actually useful (e.g. powers

> of 2), it's significantly [in a statistical sense] faster than regular math.

>

> Aseem

>

>