开发者

Are there any performance costs associated with using bitwise operators?

开发者 https://www.devze.com 2023-01-30 01:53 出处:网络
In order to reduce the amount of data being retrieved from my server by Ajax requests, I\'m planning on converting about 30 boolean fields into one binary number, and then using bitwise operators to m

In order to reduce the amount of data being retrieved from my server by Ajax requests, I'm planning on converting about 30 boolean fields into one binary number, and then using bitwise operators to make use of this data.

I haven't used bitwise operators before and was wondering if they're fast/slow in PHP and JavaScript, i.e. how does building a binary number and then comparing it with another using a bitwise operat开发者_Go百科or perform compared to just looking up a boolean value stored in an array/object?


Bitwise operations in general are the fastest operations in higher level languages. In case of PHP, they map to the underlying C, so they don't cause significant performance dropping by any means.


According to the documentation from Mozilla, bitwise operations are very slow in JavaScript since internally the numbers are treated as floating point values, not int64. So I think you should avoid using this in your JavaScript whenever possible.

In PHP, I don't know and did not see any formal documentation about this.


The only way you can do it is by measuring - although I doubt doing bitwise operations in JavaScript will get you much over an array/object.

I'd try:

var len = 100000;
var bitwise = 0xdeadbeef;
var arrays = [1,1,0,1,1,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1];
var start = new Date().getTime();
for (var i = 0; i < len; i++) {
   arrays[i % 32]; //Uncomment to test this
   //bitwise & (1 << (i % 32)); //Uncomment to test this
}
var end = new Date().getTime();
console.log((end-start)/len +"ms per access");

I got (Chrome, Windows 7, Core i7 920, 6 GB RAM):

0.0015 ms per access for arrays
0.0016 ms per access for bit shifting.

You make the decision - it is almost insignificant. Use Arrays for slightly better speed, use bitwise packing if space (bandwidth) is to be conserved.


Sure there are big performance costs - namely those of your own performance.

First, changing bool fields to bits won't optimize anything. It won't make your application any faster. Second, you said you haven't used bitwise operations before, so you'll lose a lot of time learning new stuff which is hardly useful in web programming. Third, your code gets order of magnitude less readable, which means major support and refactoring costs in the nearest future. Bottom line: don't waste your time.

0

精彩评论

暂无评论...
验证码 换一张
取 消