I often need to compare two bit arrays to see if they are identical or not, so I came with a function that doesn't look too performant to me, seems like it could be better since there are three logical operations in a single line. I'm wonder if it's posible to simplify it.
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1.Length <> ba2.Length Then
Return False
End If
Dim i As Integer
For i = 0 To ba1.Length - 1
If Not (Not ba1(i)) Xor ba2(i) Then
Return False
End If
Next
Return True
End Function
Edit:
After hours of testing and brainstorming, I came to my initial thoughts to reduce somehow the number of those three logical operators, and I put one of them into a variable, which means a single action to revert all bits at once instead of reverting bit by bit. This is the result, and is way much faster than previous one, about 3 times faster:
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1.Count <> ba2.Count Then
Return False
End If
Dim revBa1 As BitArray = ba1.Not ' <<
Dim i As Integer
For i = 0 To ba1.Count - 1
If (Not revBa1(i)) Xor ba2(i) Then ' eliminates one logical operation existing here before
Return False
End If
Next
Return True
End Function
Now, faster than this one? :) Who knows, maybe...
Edit 2:
After some more testing and unconclusive results I noticed that the second version of the function is incorrect. Although it gets the right result, but it changes the ba1 value like it were passed byRef to the function:
'------------------------
'ba1 before = 000000000000000000000000000000001
'ba2 before = 000000000000000000000000000000001
'ba1 after = 111111111111111111111111111111110
'ba2 after = 000000000000000000000000000000001
'function result = True
'------------------------
Any ideas?
Edit 3: The solution was simple, but the function isn't fast anymore:
Dim revBa1 As New BitArray(ba1)
revBa1 = revBa1.Not()
Edit 4: Yes, this is it:
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1 Is Nothing OrElse ba2 Is Nothing Then
Return False
End If
If ba1.Count <> ba2.Count Then
Return False
End If
Dim i As Integer
For i = 0 To ba1.Count - 1
If ba1(i) Xor ba2(i) Then
Return False
End If
Next
Return True
End Function
I guess sometimes we don't see the forest because of trees :)