It's going to be a lot faster than the code you posted below:
Ok. I'll give it a shot.
Secondly, the above doesn't do the test to start with about file sizes.
In my case 9999 times out of 10000, the size would be the same. Doing the
size check would therefore not improve performance more than marginally.
That is why I initially left it out.
Thirdly, there's no reason to go through a BinaryReader here - it's
just an extra level of indirection to slow things down.
Here's some code in C# which should be significantly faster:
[snip]
WHAT an increase in speed! Thanks Jon!!
I did a test with two 91kb identical files. I compared using the funtion I
posted earlier:
Average runtime per compare: 0.35sec
And then using your function:
Average runtime per compare: 0.0009sec [woooooooot]
Thanks a lot!
I included the vb-code below if anyone else is interested.
Function CompareFiles(ByVal file1 As String, ByVal file2 As String) As
Boolean
Const BufferSize As Integer = 32768
Dim fileStream1 As New System.IO.FileStream(file1, IO.FileMode.Open)
Dim fileStream2 As New System.IO.FileStream(file2, IO.FileMode.Open)
Dim buffer1() As Byte
Dim buffer2() As Byte
buffer1 = New Byte(BufferSize) {}
buffer2 = New Byte(BufferSize) {}
Dim buffer1Remaining As Integer = 0
Dim buffer2Remaining As Integer = 0
Dim buffer1Index As Integer = 0
Dim buffer2Index As Integer = 0
While True
If buffer1Remaining = 0 Then
buffer1Index = 0
buffer1Remaining = fileStream1.Read(buffer1, 0, BufferSize)
End If
If buffer2Remaining = 0 Then
buffer2Index = 0
buffer2Remaining = fileStream1.Read(buffer2, 0, BufferSize)
End If
If buffer1Remaining = 0 And buffer2Remaining = 0 Then
fileStream1.Close()
fileStream2.Close()
Return True
End If
If buffer1Remaining = 0 Or buffer2Remaining = 0 Then
fileStream1.Close()
fileStream2.Close()
Return False
End If
Dim compareSize As Integer = Math.Min(buffer1Remaining, buffer2Remaining)
For i As Integer = 0 To compareSize
i += 1
If (buffer1(buffer1Index) <> buffer2(buffer2Index)) Then
fileStream1.Close()
fileStream2.Close()
Return False
End If
buffer1Index += 1
buffer1Index += 2
Next
fileStream1.Close()
fileStream2.Close()
End While
End Function