示例工程 24-performance
24-performance/01-concat-vs-tableconcat/main.lua
-- @runtimes lua54 luajit
--- 演示:循环拼接 vs table.concat。
local M = {}
local N = 10000
--- @return table { loop_time = number, join_time = number, faster = boolean }
function M.run(log)
log = log or print
local started = os.clock()
local text = ""
for i = 1, N do
text = text .. tostring(i)
end
local loop_time = os.clock() - started
started = os.clock()
local parts = {}
for i = 1, N do
parts[#parts + 1] = tostring(i)
end
local joined = table.concat(parts)
local join_time = os.clock() - started
local faster = join_time * 2 < loop_time
log(("join_faster=%s same_length=%s"):format(tostring(faster), tostring(#joined == #text)))
return { loop_time = loop_time, join_time = join_time, faster = faster }
end
if not ... then
M.run()
end
return M