Skip to content

Instantly share code, notes, and snippets.

@lewis6991
Last active October 17, 2024 12:31
Show Gist options
  • Save lewis6991/d75181b27c8b675c84ab31eb9f459d90 to your computer and use it in GitHub Desktop.
Save lewis6991/d75181b27c8b675c84ab31eb9f459d90 to your computer and use it in GitHub Desktop.
Lua Perf

General performance tips

Efficiently remove items from an array

.. vs string.format('%s%s%s') in LuaJIT: hrsh7th/nvim-cmp#1980 (comment)

Profile Code
local ITERATION = 1000000

-- Prevents JIT compilation
local function consume(data)
  _G.data = data
end

local function run(name, f)
  collectgarbage('collect')
  collectgarbage('stop')
  local s = os.clock()
  for _ = 0, ITERATION, 1 do
    consume(f())
  end
  local e = os.clock()
  print(('%s'):format(name))
  print(('    %s seconds'):format(e - s))
  print(('    %s kb'):format(collectgarbage('count')))
  collectgarbage('restart')
end


vim.print(('Lua version %s (%s)'):format(_VERSION, type(jit) == 'table' and 'JIT' or 'PUC'))

for i = 1, 10 do
  run(('[%s] format'):format(i), function()
    local a = tostring(math.random())
    local b = tostring(math.random())
    local c = tostring(math.random())
    return string.format('%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s', a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c, a, b, c)
  end)
  run(('[%s] syntax'):format(i), function()
    local a = tostring(math.random())
    local b = tostring(math.random())
    local c = tostring(math.random())
    return (a .. b .. c .. a .. b .. c .. a .. b) .. (c .. (a .. b) .. (c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c .. a .. b .. c) .. a .. b .. c .. (a .. b .. c .. a .. b .. c) .. a .. b .. (c .. a .. b .. c) .. a .. b .. c)
  end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment