lua-users home
lua-l archive

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


On Tue, May 4, 2010 at 9:30 AM, François Perrad
<francois.perrad@gadz.org> wrote:
> The goal is to improve the performance of most of the object oriented
> implementations (prototype or class based).
> The idea is to prevent rehashing during the object instanciation.
> It will done by a new function written in C, in the Table library.
> A Lua version could be written :
>
>     function table.proto (t)
>         local tp = {}
>         for k in pairs(t) do
>             tp[k] = nil
>         end
>         return tp
>     end
>
> This function creates only the keys in the new table.
> It is not a DeepCopy, ShallowCopy, clone function, ...
> because the behaviour of this kind of function depends
> on the object model.
>
> A first implementation with Lua API was too slower.
> So, I write a second implementation with low level functions.
>
> The following code :
>     local p = { a = true, b = true, c = true, d = true, e = true }
>     local proto = table.proto
>     for i = 1, 1000000 do
>         local t = proto(p)
>         t.a = i; t.b = i; t.c = i; t.d = i; t.e = i
>     end
>
> is 2x faster than :
>     for i = 1, 1000000 do
>         local t = {}
>         t.a = i; t.b = i; t.c = i; t.d = i; t.e = i
>     end
>
> and ~10% slower than :
>     for i = 1, 1000000 do
>         local t = { a = i, b = i, c = i, d = i, e = i }
>     end
>
> François Perrad
>
>

It sounds like what you want is a Lua interface to the API function
lua_createtable():

http://www.lua.org/manual/5.1/manual.html#lua_createtable

...which takes a number of array elements and a number of hashed
elements and preallocates space for them in a newly created table.
It's easy enough to do for yourself, as long as you are in a position
to actually do stuff with the C API, but I wouldn't mind seeing this
become a standard Lua function either, as table.create() or
table.allocate() or something like that. table.proto() could then be
written as a simple Lua module on top of this.

-Duncan