Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of bitwise operators in javascript

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

like image 203
Gordon Gustafson Avatar asked Oct 06 '09 00:10

Gordon Gustafson


3 Answers

This is quite an old question, but no one seemed to answer the updated version.

The performance hit that you get with JavaScript that doesn't exist in C/C++ is the cast from floating point representation (how JavaScript strores all of its numbers) to a 32 bit integer to perform the bit manipulation and back.

like image 161
Chad Schouggins Avatar answered Sep 20 '22 23:09

Chad Schouggins


Nobody uses hex anymore?

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

var c1 = hextoRgb('#191970');
alert('rgb(' + c1.join(',') + ')');
like image 43
kennebec Avatar answered Sep 20 '22 23:09

kennebec


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

var i=3.141532;
var iTrunc=i>>0; //3
like image 29
spender Avatar answered Sep 24 '22 23:09

spender