示例工程 09-sequences-and-sparse-arrays
09-sequences-and-sparse-arrays/02-remove-shift-cost/main.lua
-- @runtimes lua54 luajit
--- 演示:table.remove 头部删除会移动元素。
local M = {}
local N = 2000
--- @return table { head_time = number, tail_time = number, head_faster = boolean }
function M.run(log)
log = log or print
local head = {}
for i = 1, N do
head[i] = i
end
local started = os.clock()
for _ = 1, N do
table.remove(head, 1)
end
local head_time = os.clock() - started
local tail = {}
for i = 1, N do
tail[i] = i
end
started = os.clock()
for _ = 1, N do
table.remove(tail)
end
local tail_time = os.clock() - started
local head_slower = tail_time * 2 < head_time
log(("head_slower=%s"):format(tostring(head_slower)))
log(("head_empty=%s tail_empty=%s"):format(tostring(#head == 0), tostring(#tail == 0)))
return { head_time = head_time, tail_time = tail_time, head_slower = head_slower }
end
if not ... then
M.run()
end
return M