LuaLS/LuaParser

Investigate if saving closures to local variables provides performance benefits

C3pa opened this issue · 3 comments

C3pa commented

Repeatedly creating a function closure in functions that are called often may lead to decreased performance. I have an example here.

 while true do
      local name
      try(function () -- This function is constantly being recreated
          local returnName = parseName('doc.return.name', typeUnit)
                          or parseDots('doc.return.name', typeUnit)
          if not returnName then
              return false
          end
          if checkToken('symbol', ':', 1) then
              nextToken()
              name = returnName
              return true
          end
          if returnName[1] == '...' then
              name = returnName
              return false
          end
          return false
      end)
      local rtn = parseType(typeUnit)
      if not rtn then
          break
      end
      rtn.name = name
      if checkToken('symbol', '?', 1) then
          nextToken()
          rtn.optional = true
      end
      typeUnit.returns[#typeUnit.returns+1] = rtn
      if checkToken('symbol', ',', 1) then
          nextToken()
      else
          break
      end
  end

Instead I propose the following:

local checkFunc = function()
  --function body here
end
while true do
  local name
  try(checkFunc())
  -- the rest of the loop here
end

The same approach can be applied to some other places with functions that constantly create new anonymous functions. These functions can be saved to a variable to avoid the VM from constantly creating (and compiling) new functions.

Are there some scripts to test the performance of changes to the parser? Of course, some kind of benchmarks before and after the changes should be used to see if my proposal improves performance.

  1. Open project in VSCode
  2. Install Lua Debug
  3. Add your tests and modify these lines: https://github.com/sumneko/LuaParser/blob/70421dd86de6a2999a1bbceb91547301fcb38c11/test/perform/init.lua#L93-L99
  4. Run debug 单元测试 (Use Ctrl+F5 instead of F5, avoid the slowdown of the debugger)

But I don't think these changes can bring significant improvements.
Unless you deliberately construct a scene to trigger the worst situation, I don't think you can see any difference at all.

C3pa commented

The proposed changes didn't provide any performance gains. For more info see #8.