cloudflare / lua-resty-logger-socket

Raw-socket-based Logger Library for Nginx (based on ngx_lua)
488 stars 130 forks source link

Make use of table.clear() when it is available #2

Closed agentzh closed 11 years ago

agentzh commented 11 years ago

The latest LuaJIT v2.1 branch implements a new Lua primitive, table.clear(), which clears all the contents in a Lua table without freeing any memory in the table itself. This is much cheaper than iterating the table ourselves with pairs() or ipairs(), and can also be JIT compiled.

We should make use of this API function when it is available in this logger library. We can fall back to the the existing way of clearing Lua tables when it is missing. Basically we can do something like this:

local ok, clear_tab = pcall(require, "table.clear")
if not ok then
    clear_tab = function (tab)
                    for k, _ in pairs(tab) do
                        tab[k] = nil
                    end
                end
end

And when we need to clear a Lua table in variable foo, we can just do

clear_tab(foo)

And that's it! :)

calio commented 11 years ago

In the current version of lua-resty-logger-socket, the buffer table is partially cleared after log messages are sent out. While flushing log messages, there would be new log messages coming into the buffer table. Because there is no whole clear is performed, so table.clear is not suitable for current version of lua-resty-logger-socket.