lua-users home
lua-l archive

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


I have a function I would like to optimize (yes, I've done profiling).
it transforms string like "3-7" into "3,4,5,6,7".

After trying out a couple of variants I still couldn't gain much.
May be someone on the list could do better.

Here are my versions:


function numeric_range_tranformer1(s)
	ctor = function(from, to)
		local n1 = tonumber(from)
		local n2 = tonumber(to)
		if n1 >= n2 then return from end
		local s = from
		for i = n1+1, n2 do
			--s = s .. "," .. tostring(i)
			s = string.format("%s,%s", s, i)
		end
		return s
	end
	return string.gsub(s, "(%d+)-(%d+)", ctor)
end


function numeric_range_tranformer2(s)
	ctor = function(from, to)
		local n1 = tonumber(from)
		local n2 = tonumber(to)
		if n1 >= n2 then return from end
		local s = from
		local t = {from}
		for i = n1+1, n2 do
			table.insert(t, i)
		end
		return table.concat(t, ",")
	end
	return string.gsub(s, "(%d+)-(%d+)", ctor)
end

Both runs on the same speed and profiling tells that most time spent in
a [for] loop.

-- 
Regards, max.