views:

619

answers:

11

One of the main ideas behind using bitwise operators in languages like C++/java/C# is that they're extremely fast. But I've heard that in javascript they're very slow (admittedly a few milliseconds probably doesn't matter much today). Why is this so?

(this question discusses when bitwise operators are used, so I'm changing the focus of this question to performance.)

+1  A: 

I use bitwise shift of zero in JS to perform quick integer truncation:

var i=3.141532;
var iTrunc=i>>0; //3
spender
That's a truly abhorrent use of the bit shift operator.
Greg Hewgill
Yes, it's filthy, I know, but actually, it had its place in games programming for Flash. In AVM1 days this was the fastest way. Don't know if that holds for JS though.
spender
var iTrunc = i|0; saves you one stroke of golf (saw this on some code-golf thread here)
Jimmy
-1 Very very ugly. Programming is about making other programmers understand what you do, NOT explictly obfuscating what you are trying to do.
Tomas
+8  A: 

When would you want to use them? You would want to use them when you want to do bitwise operations. Just like you'd use boolean operators to do boolean operations, and mathematical operators to do mathematical operations.

If you are comfortable with bitwise operators it is very natural to use them for some applications. They can be used for many purposes other than an over-optimized boolean array. Of course, these circumstances don't come up very often in Javascript programming, but that's no reason why the operators shouldn't be available.

Kip
+1  A: 

I'd think it's up to the implementer to make an operator efficient or inefficient. For example, there's nothing that prevents a JavaScript implementer from making a JITting VM, which turns a bitwise op into 1 machine instruction. So there's nothing inherently slow about "the bitwise operators in JavaScript".

Jonathan Feinberg
That's good theory, but what about in practice?
Snarfblam
@Snarfblam this 'theory' of improvement of javascript implementations has many practical precedents in the short history of javascript. Also, and I'm not sure that is e.e.coli's point as well, the CPUs all support fast bitwise operation, so there is indeed nothing inherently slow about bitwise operation at this low level, so if for some reason javascript implementation had sloppily failed to map js bitwise ops to these efficient machine ops, this could be fixed easily, and more quickly if there was any indication that this issue is effectivley a bottleneck for most uses of js.
mjv
A: 

When speed is paramount, you can use them for bit-masking: http://snook.ca/archives/javascript/storing_values/

Also, if you need to support Netscape 4, you'd use them to deal with Document.captureEvents(). Not that any respectable company would have you write JS for NS4...

splicer
Welcome to hell. you have two choices for your eternal suffering: Burn on a charcoal grill, or write JS for NS4.
Stefano Borini
A: 

I am doubtful that bitwise operation are particularly slow in javascript. Since such operations can map directly to CPU operations, which are themselves quite efficient, there doesn't appear to be any inherent characteristic of bitwise operations that would force them to be irremediably slow in javascript.
Furthermore, and as pointed out in several responses, there exist various applications of javascript which rely on bitwise operation (ex: crytography and graphics) and which are not particularly slow... (see silky and Snarfblam on this page)

Let's never the less entertain the possibility that some particular reasons caused the various implementers of javascript hosts to implement bitwise ops in a fashion that makes these slow, and see if this even matters...

Although javascript has been used for other purposes, the most common use of this language in in providing user interface type of services.
BTW, I do not mean this in any pejorative way at all; performing these smart UI functions, and considering various constraints imposed on the language and also the loose adherence to standards, has required -and keeps requiring- talented javascript hackers.
The point is that in the context of UI-type requirements, the need for any quantity of bitwise operations susceptible of exposing the alleged slowness of javascript in handling such operations is uncommon at best. Consequently, for typical uses, programmers should use bitwise operations where and if this approach seems to flow well with overall program/data and they should do so with little concern for performance issues. In the unlikely case of performance bottleneck arising from bitwise use, one can always refactor things, but one is better off staying clear from early optimization.

The notable exception to the above is with the introduction of canvas, on modern browsers, we can expect that more primitive graphic functions will be required of javascript hosts, and such operations can require in some cases heavy doses of bitwise operations (as well as healthy does of math functions). It is likely that these services will eventually be supported by way of javascript libraries (and even end-up as languages additions). For such libraries the common smarts of the industry will have been put to use to figure out the most efficient approaches. Furthermore and if indeed there is a weakness in javascript performance with bitwise ops, we'll get some help, for I predict that the javascript implementations on various hosts (browsers) will be modified to improve this particular area. (This would follow the typical pattern of evolution of javascript, that we've seen over the years.)

mjv
A: 

People do interesting things in JavaScript.

For example there are a lot of cryptography algorithms implemented in it (for various reasons); so of course bitwise operators are used.

Noon Silk
+1  A: 

There is an NES emulator written in JavaScript - it seems to make plenty of use of bitwise operations.

Andrew Medico
+2  A: 

I found some good info @ http://dreaminginjavascript.wordpress.com/2009/02/09/bitwise-byte-foolish/

Apparently they perform very well these days. Why would you use them? Same reason you would anywhere else.

Snarfblam
+1  A: 

Nobody uses hex anymore?

function hextoRgb(c){
 c= '0x'+c.substring(1);
 c= [(c>> 16)&255, (c>> 8)&255, c&255];
 return c;
}

var c1= hextoRgb('#191970'); alert('rgb('+c1.join(',')+')');

kennebec
+1 for a real world example that's not contrived.
Kip
A: 

Using JavaScript in its Windows Scripting Host JScript incarnation, you might have cause to use bitwise operators to pick out flags in values returned from WMI or Active Directory calls. For example, the User Access value of a user's record in AD contains several flags packed into one long integer.

ADS_UF_ACCOUNTDISABLE = 0x00000002;

if (uac & ADS_UF_ACCOUNTDISABLE == ADS_UF_ACCOUNTDISABLE) {
  // user account has been disabled
}

Or someone's arbitrary table structure may contain such a field, accessible through ADO with JScript.

Or you may want to convert some retrieved data into a binary representation on any platform, just because:

BinaryData = "L";
BinaryString = BinToStr(BinaryData, ".", "x");

// BinaryString => '.x..xx..'

So there are numerous reasons why one might want to do bit manipulation in JavaScript. As for performance, the only way to know is to write it and test it. I suspect in most cases it would be perfectly acceptable, not significantly worse than any other of the multitude of inefficiencies these systems contain.

Todd
A: 

A lot of bitwise operations are being benchmarked here: http://jsperf.com/rounding-numbers-down/3

However, feel free to create your own performance testcase on jsPerf!

Mathias Bynens