- I agree with the general goal here, but I would like to request functional scope instead of a stack. This is analogous to how "use strict" works as well.

So it would be great if I could disallow bitwise operators in general, and allow it inside of an optimized mathematical function. What do you think of this? - On 04/09/09 22:01, aseem.kishore@... wrote:
> --- In jslint_com@yahoogroups.com, Stefan Weiss <weiss@...> wrote:

Much better, thank you. I didn't have the time to cook up a test myself

>> 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.

>

> 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?

earlier, and this pretty much confirms what I expected.

> Using bitwise operators seems to have no performance penalty, and in

I wasn't expecting to see a performance penalty. My point is that

> cases where it's actually useful (e.g. powers of 2), it's significantly

> [in a statistical sense] faster than regular math.

JavaScript isn't C, and micro-optimizations using bit shifts won't bring

any real advantage over normal arithmetic operations. (They're not very

helpful in C anymore either, because modern compilers are all about

optimization, and can do this sort of thing in their sleep.) It won't

make much of a difference whether you write "i << 10" or "i * 1024".

In your specific case, the performance gain is real, and apparently it's

mostly due to avoiding the method call (unless you wrap the bit shifting

it in a function, of course).

When I'm not in a tight loop, I tend to go for the most readable

implementation, even if it means using objects and properties instead of

bit fields.

cheers,

stefan