lua-users home
lua-l archive

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


The constants in function prototype could be string, number, boolean, and nil now. But some times we want to use a table as a constant object, like this:

-- iterate a immutable sequence :
for _, v in ipairs { "one", "two", "three" } do 
   -- ...
end

or like this :

function f()
  return { x=1, y = 2}
end

{ x=1, y=2 } may be a constant table. We don't modify it later.

If these kind of table constants can be hold in function prototype, it would be faster  (maybe 3-4 times faster, see the test below) and cheaper. We only need create a table proxy hold a c pointer to the table constant in the prototype.

If we modify the table later, simply clone the constant to turn the table proxy into a real table first. 

I have already try to do a quick and dirty implementation, 
https://github.com/ejoy/lua/tree/consttable

This is the patch: https://github.com/ejoy/lua/commit/a940a405ba32d0b35b91e87172d7d0503cf9e5f5

It add two opcode OP_NEWTABLEK and OP_NEWTABLEKX to support table constants. If table constructor in parser find all the keys and values of the table are constants , it add a constant table in prototype, and use new opcode .

btw, I haven't implement dump/undump now.

---- test 1 ---
function f(a)
end

local t = os.clock()

for i=1, 10000000 do
f { x=1, y=2 }
end

print(os.clock() -t)
-------------
Origin version of lua 5.3.2 : 4.977s
Modified version of lua 5.3.2: 1.278s

---- test 2 ---
function f(a)
   a.x = 3
end

local t = os.clock()

for i=1, 10000000 do
f { x=1, y=2 }
end

print(os.clock() -t)
-------------
Origin version of lua 5.3.2 : 5.234s
Modified version of lua 5.3.2: 1.413s