[Mono-dev] What's the most efficient way to do XOR two byte arrays?

Edward Ned Harvey (mono) edward.harvey.mono at clevertrove.com
Wed Nov 19 02:18:14 UTC 2014

Obviously, I could just use a for-loop.  But then my code is theoretically telling the system to XOR each byte individually, wasting most of the CPU on each instruction.

I wrote unsafe code to do this with 32-bit and 64-bit int pointers.  Surprisingly they both performed about the same (I guess, at least on my system, 64bit instructions take longer to execute, effectively eliminating most of the gains of the wider bus).  Unsurprisingly, they greatly outperformed the unoptimized for-loop.

Surprisingly, the difference between the optimized unsafe code and the optimized for-loop suggested it was a waste of effort.  (Only marginally faster.)

I don't know what kind of optimizations the compilers are able to perform on this code:

for (int i=0; i<buf1.Length; i++) {
    buf2[i] = (byte)(buf1[i] ^ buf2[i]);

I am surprised if that optimizes so well as to literally make it a waste of time to pursue anything better.  But if someone here says so, I'll have to believe you.

I haven't benchmarked, but rumor on the internet suggests that the for-loop for copying bytes from one buffer to another is slow compared to Array.Copy, which is slower still than Buffer.BlockCopy.  Assuming this is correct, I have to assume it's possible to have an optimized method of XOR'ing blocks of data too.  But I haven't found any such method in .Net.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20141119/d376a02c/attachment.html>

More information about the Mono-devel-list mailing list