Thursday, June 11, 2015

A little optimization trick for Corona SDK/lua using first-class function

Many times during development of  my games using Corona SDK I found that I have a function that gets called a lot, and at the beginning of the function I need to check for state of the game.  Something like this:


function listener(e)
     if state == S_PAUSED then return end
    
    -- OK, do real stuff
end


Every time this function gets called, the if statement gets executed, and in this case it is a wasteful since the game is not paused most of the time.  To get rid of this overhead, I often use a feature known as first-class function, which basically means you can treat a function as if it's variable so that you can pass it around or return it from other functions.

So, with first-class function, we can reconstruct our program like this


local listener

function listener_pause(e)
   -- do nothing
end


function listener_ready(e)
   -- OK, do real stuff
end


function setPause(v)
    if v then
        listener = listener_pause
    else
        listener = listener_ready
    end
end

listener = listener_ready


When the program is paused, the function listener_pause() gets called and do nothing, just like the original function.  However, if program is not paused, the function listner_ready() is the one that gets executed, and there is no overhead.

The downside of this method is that your program will be a bit longer, but it might worth it if the function get called a lot, like maybe the one that responds to 'enterFrame' event.

No comments:

Post a Comment