lua-users home
lua-l archive

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



On 23/01/15 04:35 PM, Hisham wrote:
On 23 January 2015 at 13:44, Soni L. <fakedme@gmail.com> wrote:
How can I quickly concatenate 2 tables? (or convert a whole string to a
table of bytes/numbers)

For example:

local t = {string.byte(str, 1, stack_limit)} .. {string.byte(str,
stack_limit+1, stack_limit*2)} -- .. etc

Or:

local t = string.bytearray(str)

Both of them would be much faster (and human-friendly) than this:

local t1 = {string.byte(str, 1, stack_limit)}
local t2 = {string.byte(str, stack_limit+1, stack_limit*2)}
local t = t1
for k,v in ipairs(t2) do
   t[k+stack_limit] = v
end
-- etc
--os.execute("dd if=/dev/urandom of=file bs=1M count=1")
local fd = io.open("file")
local longstr = fd:read("*a")
fd:close()

-- time: about 0.17 on Lua 5.2
-- time: about 0.19 on Lua 5.3
-- time: about 0.02 on LuaJIT
local function strarray(longstr)
     local t = {}
     for i = 1, #longstr do
        t[i] = longstr:byte(i)
     end
     return t
end

-- time: about 0.11 on Lua 5.3
-- time: about 0.11 on Lua 5.2 + compat53
-- time: about 0.08 on LuaJIT + compat53
local function strarray2(longstr)
     -- tuning the step does not affect speed much
     -- (for this example size, at least.)
     local step = 500
     local t = {}
     for i = 1, #longstr, step do
        local u = { longstr:byte(i, i+step) }
        table.move(u, 1, #u, i, t)
     end
     return t
end

-- time: about 0.11 on Lua 5.2
-- time: about 0.14 on Lua 5.3
-- time: about 0.03 on LuaJIT
local function strarray3(longstr)
     local step = 500
     local t = {}
     for i = 1, #longstr, step do
        local u = { longstr:byte(i, i+step) }
        for m = 1, #u do
            t[i+m-1] = u[m]
        end
     end
     return t
end

local function dump(t)
     for i = 1, #t, 16 do
         for x = 0, 15 do
            io.write( ("%02x "):format(t[i+x]) )
         end
         io.write("\n")
     end
end

local function check(t1, t2)
     if #t1 ~= #t2 then return false end
     for i = 1, #t1 do
        if t1[i] ~= t2[i] then return false end
     end
     return true
end

local t = strarray(longstr)
--local t2 = strarray2(longstr)
--local t3 = strarray3(longstr)
--print(check(t, t3))
--dump(t)

Damn LuaJIT beats everything >.>

What about C?

--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.