简体   繁体   English

使用Javascript ArrayBuffer执行XOR的最快方法

[英]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

  • the native ^ operator 本机^运算子
  • (n1+n2)%2
  • n1+n2-2*n1*n2
  • use a preset array: 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.

相关问题 有没有办法从 ArrayBuffer 创建 TypedArray 而不在 Javascript 中使用 new 关键字? - Is there a way to create a TypedArray from an ArrayBuffer without using new keyword in Javascript? Javascript:使用XMLHttpRequest发送arrayBuffer - Javascript: Sending arrayBuffer using XMLHttpRequest 使用javascript查找元素位置的最快方法? - fastest way to find element position using javascript? 在Javascript Hashmap中使用坐标作为键的最快方法 - Fastest Way of Using Coordinates as Keys in Javascript Hashmap 使用Javascript格式化纯文本的最快方法 - Fastest Way To Format a Plain Text Using Javascript "有没有办法在Android上将arraybuffer从javascript传递到java?" - Is there a way to pass an arraybuffer from javascript to java on Android? 这是使用jQuery将XML解析为JavaScript对象的最快方法吗? - Is this the fastest way to parse my XML into JavaScript objects using jQuery? 使用Javascript遍历兄弟姐妹的最快方法是什么? - What is the fastest way to iterate through siblings using Javascript? 使用javascript获取域/主​​机名的最快方法 - Fastest way to grab domain/host name using javascript 使用JavaScript将HTML内容附加到div的最快方法 - Fastest way to append HTML content to a div using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM