Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to do bitwise operations on pairs of elements in two ArrayBuffers in Javascript

I have two Javascript ArrayBuffers; each contains 512 bits of data. I would like to do an xor comparison of the two arrays and store the results in a third array.

Currently, I am looping over the elements in the buffers. In the code below 'distance' is an integer and feat_a1 and feat_b1 are ArrayBuffers that are 512 bits in length.

for(var d1=0; d1<512; d1++){
  distance += feat_b1[d1] ^ feat_a1[d1];
}

Is there a more efficient way of doing the pairwise comparison of these two arrays?

like image 960
freakTheMighty Avatar asked Feb 03 '14 16:02

freakTheMighty


People also ask

Is bit shifting faster than addition?

I came across this excerpt today: On most older microprocessors, bitwise operations are slightly faster than addition and subtraction operations and usually significantly faster than multiplication and division operations.

How do bitwise operators work in JavaScript?

Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and ones) and perform actions. However, the result is shown as a decimal value. Note: The minimum and the maximum integers that are representable through a 32-bit signed number are -2147483648 to 2147483647.

What is ArrayBuffer in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

Does JavaScript have bitwise operators?

JavaScript Bitwise Operations JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.


1 Answers

as i understand you can't directly use arrayBuffer[i], you have to pass it to some container (like Int8Array). I have made next example http://jsfiddle.net/mLurz/ , tried with different Typed arrays from this list and Uint32Array showed the best performance

var i;
var dist = 0;
var max = Math.pow(2,32);
var buf1 = new ArrayBuffer(1024);
var x = new Uint32Array(buf1);
for (i = 0; i < 256; ++i) {
    x[i] = Math.random()*max;
}

var buf2 = new ArrayBuffer(1024);
var y = new Uint32Array(buf2);
for (i = 0; i < 256; ++i) {
    y[i] = Math.random()*max
}

console.time('Uint32Array');
for (var j = 0; j < 1000000; ++j) {
    for (i = 0; i < 256; ++i) {
        dist += y[i]^x[i];
    }
}
console.timeEnd('Uint32Array');
like image 110
Vlad Nikitin Avatar answered Sep 27 '22 20:09

Vlad Nikitin