lua-users home
lua-l archive

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


local assert = assert

local function f(a)
    assert(a.c.e == 3)
    a.c.e = 4
end

local t = os.clock()

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

print(os.clock() -t)


assert failed with constable branch...

On Apr 12, 2016, at 16:41, 云风 Cloud Wu <cloudwu@gmail.com> wrote:

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, 


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