lua-users home
lua-l archive

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


Javier Guerra wrote:
On 2/21/08, Mike Pall <mikelu-0802@mike.de> wrote:
local t = setmetatable({}, { __index = function() return 0 end })
 for c in string.gmatch(io.read("*a"), ".") do t[c] = t[c] + 1 end
 table.foreach(t, print)

very neat!

now, which way is the fastest?

hard to measure, but the lpeg variant is slightly faster

data = string.rep("a",10*1000*1000)

collectgarbage("collect")
t = os.clock()
cc = setmetatable({}, { __index = function() return 0 end })
for c in data:gmatch(".") do cc[c] = cc[c] + 1 end
print(os.clock()-t)

collectgarbage("collect")
t = os.clock()
cc = setmetatable({}, { __index = function() return 0 end })
lpeg.match((lpeg.P(1) / function(c) cc[c] = cc[c] + 1 end)^0,data)
print(os.clock()-t)

collectgarbage("collect")
t = os.clock()
local function add(c) cc[c] = cc[c] + 1 end
cc = setmetatable({}, { __index = function() return 0 end })
lpeg.match((lpeg.P(1) / add)^0,data)
print(os.clock()-t)



-----------------------------------------------------------------
                                          Hans Hagen | PRAGMA ADE
              Ridderstraat 27 | 8061 GH Hasselt | The Netherlands
     tel: 038 477 53 69 | fax: 038 477 53 74 | www.pragma-ade.com
                                             | www.pragma-pod.nl
-----------------------------------------------------------------