示例工程 06-control-flow-and-truthiness

06-control-flow-and-truthiness/06-dispatch-bench/main.lua

lua · 1.0 KB

-- @runtimes lua54 luajit
--- 演示:if 链与函数表分派的相对成本。
 
local M = {}
 
local N = 200000
 
--- @return table { chain = number, table_time = number, chain_sum = number, table_sum = number }
function M.run(log)
	log = log or print
	local ops = {
		add = function(a, b)
			return a + b
		end,
		mul = function(a, b)
			return a * b
		end,
	}
	local chain_sum = 0
	local started = os.clock()
	for i = 1, N do
		local op = "add"
		local value
		if op == "add" then
			value = i + 1
		elseif op == "mul" then
			value = i * 2
		else
			value = 0
		end
		chain_sum = chain_sum + value
	end
	local chain = os.clock() - started
 
	local table_sum = 0
	started = os.clock()
	for i = 1, N do
		local value = ops.add(i, 1)
		table_sum = table_sum + value
	end
	local table_time = os.clock() - started
	log(("chain_positive=%s"):format(tostring(chain_sum > 0)))
	log(("table_positive=%s"):format(tostring(table_sum > 0)))
	return { chain = chain, table_time = table_time, chain_sum = chain_sum, table_sum = table_sum }
end
 
if not ... then
	M.run()
end
 
return M