Re: Adding assembler code to Lua programs

  • From: Mike Pall <mike-1403@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 7 Mar 2014 10:42:27 +0100

Konstantin Olkhovskiy wrote:
> I had a wild idea of implementing attribute extractor with
> DynASM that will craft some specialized piece of code that skips
> unnecessary fields and retrieves the one(s) requested. Is it
> sensible to use DynASM for this purpose? Or Lua version can
> JIT-compile in something comparable in performance?

Dynamically generate Lua source code that scans the data using
the FFI. Something like this, where d is an FFI struct
(untested code, typed into the mail):

  local function match_factory(match_list)
    -- lookup match function cache here

    -- Otherwise generate new match function.
    local s = [[
      -- Place any immutable upvalues or other dependencies here.
      return function(d)
        return
    ]]

    local first = true
    -- Some loop which accumulates the fields to be checked from match_list
      if not first then s = s .. " and "; first = false end
      -- Example: equality check for an integer field.
      s = s .. string.format("d[i].%s == %d", field_name, field_value)
    -- ...

    s = s .. [[
      end
    ]]

    local match = loadstring(s)()
    -- Cache match here.
    return match
  end

  ... call it later e.g. to process an array of structs ...
  local match = match_factory(match_list)
  for i=1,n do
    if match(a[i]) then ... end
  end

That's pretty easy for the JIT compiler to optimize -- provided
the loop is on the Lua side. Only go the DynASM route if that
approach doesn't perform.

--Mike

Other related posts: