[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Speed optimized base64 encoder for Lua 5.3
- From: Michael Welsh Duggan <mwd@...>
- Date: Tue, 04 Nov 2014 12:21:49 -0500
Ico Doornekamp <lua@zevv.nl> writes:
> I wrote the snippet below today to speed up the base64 encoding in my
> application using the new binary operators in Lua5.3, it might be of use for
> others. I think the algorithm is pretty much optimal, but I'm open to any
> suggestions and improvements.
[...]
> local function base64(s)
> local byte, rep = string.byte, string.rep
> local pad = 2 - ((#s-1) % 3)
> s = (s..rep('\0', pad)):gsub("...", function(cs)
> local a, b, c = byte(cs, 1, 3)
> return bs[a>>2] .. bs[(a&3)<<4|b>>4] .. bs[(b&15)<<2|c>>6] .. bs[c&63]
> end)
> return s:sub(1, #s-pad) .. rep('=', pad)
> end
A couple trivial optimization change: move the following line:
local byte, rep = string.byte, string.rep
out of the function. The string table look-ups happen every single
call, rather than only once at load time.
It is also possible that lifting string.sub and string.gsub out the same
way as byte and rep and using them via upvalue may be faster than doing
a metatable look-up each time through.
--
Michael Welsh Duggan
(mwd@cert.org)