lua-users home
lua-l archive

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


Put the sample code in a file of its own and compile it with luac -l
You'll see that the second one performs more move operations than the first.

So the basic rule is - keep scopes small if possible, both for performance and readability.
It seems that your assumption was that "local" performs some sort of operation in runtime, which is why you moved it outside of the loops. This is false.

local a, b, c = foo() -- this tells the compiler to put a, b, c at the same place as the result of the call would have placed them, so they don't need any move operations.
local a, b, c;
...
a, b, c = foo() -- this does the equivalent of first doing local _a, _b, _c = foo() and then does a, b, c = _a, _b, _c, which is more move operations.

Sample code
----------------
function a()
    for y = y0 , y1 do
         for x = x0, x1 do
             local v = get_value(x,y)
             local r,g,b = get_rgb(x,y)
        end
    end
end

function b()
    local v, r,g,b
    for y = y0 , y1 do
         for x = x0, x1 do
             v = get_value(x,y)
             r,g,b = get_rgb(x,y)
        end
    end
end


On Tue, Oct 5, 2010 at 11:14 AM, Thierry <th.douez@sunnyrevtalk.com> wrote:
Hi,

Learning Lua, I'm a bit puzzled with this test :

Could someone explain why the first script below is about 10%
faster than the second ?

Intuitively, I would have guessed the opposite.

Thanks
Thierry


    for y = y0 , y1 do
         for x = x0, x1 do
             local v = get_value(x,y)
             local r,g,b = get_rgb(x,y)
             <....../>
        end
    end

    local v, r,g,b
    for y = y0 , y1 do
         for x = x0, x1 do
             v = get_value(x,y)
             r,g,b = get_rgb(x,y)
             <....../>
        end
    end