lua-users home
lua-l archive

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


Here is one more version, still not lj2 friendly, but for some reason very much lua friendly (no closure, using directly next iterator):

malkia ~/p/luamarca $ ./run_benchmark.sh bench/tclone.lua 100000
Results:
lua
-------------------------------------------------------------------
                name |     rel | abs s / iter = us (1e-6 s) / iter
-------------------------------------------------------------------
             tclone6 |  1.0000 |   2.94 /     100000 = 29.400000 us
             tclone5 |  4.9592 |  14.58 /     100000 = 145.800000 us
             tclone2 |  5.6190 |  16.52 /     100000 = 165.200000 us
          lua_nucleo |  5.8401 |  17.17 /     100000 = 171.700000 us
luajit -O
-------------------------------------------------------------------
                name |     rel | abs s / iter = us (1e-6 s) / iter
-------------------------------------------------------------------
             tclone6 |  1.0000 |   1.45 /     100000 = 14.500000 us
             tclone5 |  1.1103 |   1.61 /     100000 = 16.100000 us
             tclone2 |  1.3034 |   1.89 /     100000 = 18.900000 us
          lua_nucleo |  1.5241 |   2.21 /     100000 = 22.100000 us

local tclone6
do
  local function impl(t, visited, rtimes)
    if visited[t] then
      error("recursion detected")
    end

    if rtimes == 128 then
      rtimes = 1
      visited[t] = true
    end

    local r = {}
    local k, v = next(t)
    while k do
       if type(k) == "table"  then
	  if type(v) == "table" then
	     r[impl(k, visited, rtimes + 1)] = impl(v, visited, rtimes + 1)
	  else
	     r[impl(k, visited, rtimes + 1)] = v
	  end
       elseif type(v) == "table" then
	  r[k] = impl(v, visited, rtimes + 1)
       else
	  r[k] = v
       end
       k, v = next(t, k)
    end

    if rtimes == 1 then
      visited[t] = nil
    end

    return r
  end

  tclone6 = function(t)
    if type(t) == "table" then
      return impl(t, { }, 1)
    end

    return t
  end
end


On 8/22/11 9:37 AM, Dimiter "malkia" Stanev wrote:
On 8/22/11 3:29 AM, Alexander Gladysh wrote:
On Sun, Aug 21, 2011 at 05:03, Dimiter "malkia"
Stanev<malkia@gmail.com> wrote:
Here is a little bit more optimized version.

<...>

Thank you, very interesting!

Can I reuse it in lua-nucleo (under MIT license)?

Alexander.



Yes, no problem, and license of your choosing (I usually go with MIT
too, as lua and luajit are there, no need to make it more complex).

Cheers!