lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, 17 Apr 2010 02:39:00 +0300, Valerio Schiavoni
<valerio.schiavoni@gmail.com> wrote:

Hello,
profiling my application, the big bottleneck of it comes from this function:

function string2hex(str)
assert(str,"String2hex got null argument")
 local h,s =  string.gsub(str, "(.)", function(c) return
string.format("%02X", string.byte(c)) end)
return h
end


The size of input strings can be from 1kb to 1Mb.
How would you optimize it ?


thanks for any suggestion,
valerio

Check p24. in this document: http://www.lua.org/gems/sample.pdf
gsub will create the anonymous function each time it's called. If you put
it outside the block, it'll surely speed up the mechanism:

function string2hex(str)
	assert(str,"String2hex got null argument")
	local hex = function(c) return string.format("%02X", string.byte(c)) end
	local h,s =  string.gsub(str, "(.)", hex)
	return h
end
But Patrick's code snippets might be even better. All in all, it's highly recommended to read that book (or at least that part).