[英]Fastest way to perform XOR using Javascript ArrayBuffer
I have a class representing bits and it uses ArrayBuffers
to store the binary data. 我有一个表示位的类,它使用
ArrayBuffers
存储二进制数据。 I'm trying to figure out if there is a faster method to perform a xor
between two ArrayBuffers
. 我试图找出是否有一个更快的方法来执行两个
ArrayBuffers
之间的xor
。
Note The length of the ArrayBuffers
are usually less than 10 bytes. 注意
ArrayBuffers
的长度通常小于10个字节。 But since the xor
operation is performed millions, if not billions of times, every millisecond saved matters. 但是,由于执行了
xor
操作数百万次(即使不是数十亿次),因此每毫秒节省的时间很重要。
// my current/simple method
// assume 'buf1', 'buf2' & 'result' are ArrayBuffers
for (var i=0; i<result.length; i++) {
result[i] = buf1[i] ^ buf2[i];
}
Note Seeking solution executable both locally and on browser. 注意在本地和浏览器上寻求解决方案可执行文件。
I know of 4 ways to calculate XOR
: 我知道4种计算
XOR
:
^
operator ^
运算子 (n1+n2)%2
n1+n2-2*n1*n2
xor=[[0,1],[1,0]]
xor=[[0,1],[1,0]]
I ran the following code, you can see the results for yourself: 我运行了以下代码,您可以自己查看结果:
buf1=new Array(10000).fill(1).map((x)=>Math.floor(Math.random()*2)); buf2=new Array(10000).fill(1).map((x)=>Math.floor(Math.random()*2)); console.time('go'); for (let i=0;i<10000;i++) r=buf1[i]^buf2[i]; console.timeEnd('go'); console.time('go'); for (let i=0;i<10000;i++) r=(buf1[i]+buf2[i])%2; console.timeEnd('go'); console.time('go'); for (let i=0;i<10000;i++) r=buf1[i]+buf2[i]-2*buf1[i]*buf2[i]; console.timeEnd('go'); xor=[[0,1],[1,0]]; console.time('go'); for (let i=0;i<10000;i++) r=xor[buf1[i]][buf2[i]]; console.timeEnd('go');
All the methods seem to give similar results. 所有方法似乎都给出相似的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.