示例工程 04-strings
04-strings/02-concat-cost/main.lua
-- @runtimes lua54 luajit
--- 演示:循环里 .. 拼接 vs table.concat。
local M = {}
local N = 20000
--- @return table { loop_time = number, join_time = number, concat_faster = boolean }
function M.run(log)
log = log or print
local parts = {}
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()
for i = 1, N do
parts[#parts + 1] = tostring(i)
end
local joined = table.concat(parts)
local join_time = os.clock() - started
local concat_faster = join_time * 2 < loop_time
log(("concat_faster=%s"):format(tostring(concat_faster)))
log(("same_length=%s"):format(tostring(#joined == #text)))
return { loop_time = loop_time, join_time = join_time, concat_faster = concat_faster }
end
if not ... then
M.run()
end
return M