And here is the one with the later trick:
VB Code:
Public Function XorEncode2(ByVal strMessage As String, ByVal strKey As String) As String
Dim bArrMessage() As Byte, bArrKey() As Byte, bArrOutput() As Byte
Dim msgSize As Long, keySize As Long
Dim I As Long, A As Long, B As Byte
'convert strings to byte arrays
bArrMessage = strMessage
bArrKey = strKey
msgSize = UBound(bArrMessage) 'upper bound
keySize = LenB(strKey) 'actual size (due to the way used with Mod)
'prepare output buffer
ReDim bArrOutput(msgSize)
'without Unicode string support (step by two)
For A = 0 To keySize - 1 Step 2
B = bArrKey(A)
For I = A To msgSize Step keySize
bArrOutput(I) = bArrMessage(I) Xor B
Next I
Next A
'convert byte array to string
XorEncode2 = bArrOutput
End Function
Comparison on my machine (compiled, all advanced optimizations) with 100 000 iterations:
- XorEncode: 320 ms
- XorEncode2: 275 ms
- just the string conversion stuff, reserving of memory and function call: 260 ms
Note I really had a long pause between coding it, I did it because I had nothing better to do at the time :D
Another note for those who might come and claim using For...Next loops are slower than Do loops: in this case and use, For loops are slightly faster. No major speed difference can be gained using Do loops instead.
Edit Simplified it a bit while the speed remained the same.
Edit Slight optimization, increase in overall speed by 10ms.