Caching an expensive row-by-row table calculation between individual function calls in Lua

I have a number of functions working on strings to extract interesting properties from these strings. One specific function, called many of these functions, is very expensive and ultimately generates a table of values:

local function expensive(s)
  local t = nil
  return function()
    if not t then
      t = {}
      -- some expensive operations with s which add items to t
    end
    return t
  end
end

local function fn1(s)
  local t = expensive(s)
  -- some other fast operations using t and s
end

local function fn2(s)
  local t = expensive(s)
  -- some other fast operations using t and s
end

local s1, s2 = 'a', 'b'
fn1(s1) -- should create the 't' table for s1
fn1(s2) -- should create the 't' table for s2
fn2(s1) -- should not create the 't' table again for s1
fn1(s2) -- should also not create the 't' table again for s2

How can I make an expensive function create a table exactly once in a row, returning a table anyway? I would prefer that the table is not presented to the global environment. I think this can probably be achieved with some clever use of closures, but I don't know the construction well enough.

+4
source share
3 answers

Egor , cache . , . - do/end.

local expensive
do
    local cache = {}
    expensive = function (s)
      local t = cache[s]
      if not t then
        t = {}
        -- some expensive operations with s which add items to t
        cache[s] = t
      end
      return t
    end
end

- .

local expensive = (function ()
    local cache = {}
    return function (s)
      local t = cache[s]
      if not t then
        t = {}
        -- some expensive operations with s which add items to t
        cache[s] = t
      end
      return t
    end
end)()

, expensive , , , do/end. .

+1
local cache = {}

local function expensive(s)
  local t = cache[s]
  if not t then
    t = {}
    -- some expensive operations with s which add items to t
    cache[s] = t
  end
  return t
end
+4

You can use "memoization" to cache the values ​​returned by the function, depending on the parameters. You can read the chapter about it in the Program in Lua and use one of the memoization modules that do your work, for example memoize .

See also this SO answer for relevant interesting solutions.

+2
source

Source: https://habr.com/ru/post/1677477/


All Articles