title: What is the fastest way to compare two byte arrays?
body: <p>I am trying to compare two long bytearrays in VB.NET and have run into a snag. Comparing two 50 megabyte files takes almost two minutes, so I'm clearly doing something wrong. I'm on an x64 machine with tons of memory so there are no issues there. Here is the code that I'm using at the moment and would like to change.</p>
  
  <p><code>_Bytes</code> and <code>item.Bytes</code> are the two different arrays to compare and are already the same length.</p>
  
  <pre><code>For Each B In item.Bytes
     If B &lt;&gt; _Bytes(I) Then
          Mismatch = True
          Exit For
     End If
     I += 1
  Next
  </code></pre>
  
  <p>I need to be able to compare as fast as possible files that are potentially hundreds of megabytes and even possibly a gigabyte or two. Any suggests or algorithms that would be able to do this faster?</p>
  
  <p><code>Item.bytes</code> is an object taken from the database/filesystem that is returned to compare, because its byte length matches the item that the user wants to add. By comparing the two arrays I can then determine if the user has added something new to the DB and if not then I can just map them to the other file and not waste hard disk drive space.</p>
  
  <p>[Update]</p>
  
  <p>I converted the arrays to local variables of Byte() and then did the same comparison, same code and it ran in like one second (I have to benchmark it still and compare it to others), but if you do the same thing with local variables and use a generic array it becomes massively slower. I’m not sure why, but it raises a lot more questions for me about the use of arrays.</p>