Corona Quick Thought – a reasonably fast 8-bit XOR in native Lua

I recently had a small need for a bitwise XOR, and was disappointed that Corona’s bit plugin is only available at Pro (or Enterprise) subscription levels.

Drat. My need wasn’t great enough to justify that expense. Though note that if you do have need for thousands of XOR’s, particularly if 16- or 32-bit, then you may indeed need the native code of the plugin — interpreted Lua simply can’t match that performance. But if your needs are more modest, then perhaps there’s an alternative…

For myself, I headed off to the Lua Wiki where I knew there to be several pure Lua implementations.

Alas, while there are many capable implementations listed there, they’re all just a bit too capable for my purposes. Because the downside of being fully capable (dealing with 32-bit quantities, etc) and general-purpose means that their performance isn’t very snappy on a mobile device.

I just needed a special-purpose 8-bit xor, for dealing with values you might obtain from string.byte(), for example. So I scoured the list archive and found what looked like a good starting point. (and I couldn’t have aksed for a better authority than Roberto! 🙂 )

Basically all I’ve done here is just cripple it a bit, for 8-bit use only, then unrolled the loop and removed some intermediate values where not reused, just to gain back a bit of performance.

That’s about as far as it made sense for me to optimize. (I suppose you could duplicate and premultiply the table to save that final multiply, but it won’t make much difference. Or memoize it out to the full 64K,.. yikes. etc. My feeling was once you start contemplating those sorts of drastic measures, then you should just be using the bit plugin instead.)

And here’s a simple validation suite against the bit plugin:

Leave a Reply