分支判断条件为字符串,查表与if/else
好奇写了段代码测试:
local function foo()
end
local function bar()
end
local function baz()
end
local function branch1(s)
if s == "kjlajsdkajdkjasd" then
foo()
elseif s == "nzxnmcbzmnxcbzmx" then
bar()
elseif s == "uqoweuoqweuioooiuqwe" then
baz()
end
end
local t = {
["kjlajsdkajdkjasd"] = foo,
["nzxnmcbzmnxcbzmx"] = bar,
["uqoweuoqweuioooiuqwe"] = baz
}
local function branch2(s)
(t[s])()
end
local function branch3(s)
-- 此处Lua并没有做优化,每一次调用都会重新创建Table,所以费时大大增加,如果移到funciton外,则费时相当
(({
["kjlajsdkajdkjasd"] = foo,
["nzxnmcbzmnxcbzmx"] = bar,
["uqoweuoqweuioooiuqwe"] = baz
})[s])()
end
local function call(branch)
return function()
branch("kjlajsdkajdkjasd")
branch("nzxnmcbzmnxcbzmx")
branch("uqoweuoqweuioooiuqwe")
end
end
local function timeit(func)
local start = os.clock()
for i = 1, 1000000 do
func()
end
print(os.clock() - start)
end
timeit(call(branch1))
timeit(call(branch2))
timeit(call(branch3))
branch1和branch2耗时相差无几,而branch3则为6倍。根据查询到的相关信息,查询分支较少的时候,if else比hash算法快,反之则hash快。而branch3为何如此之慢是因为每次执行都new了table,所以对于固定的table应该放在函数外面。
清空表与创建新表
需要频繁清空表的时候,创建新表快吗?
local function timeit(func, ...)
local start = os.clock()
func(...)
print(os.clock() - start)
end
local loop = 1000000
local t = {}
local function add_data()
t.a = 1
t.b = "HelloHelloHelloHelloHelloHelloHelloHello"
t.c = 3.1415926
end
timeit(
function()
for i = 1, loop do
add_data()
t = {}
end
end
)
t = {}
timeit(
function()
for i = 1, loop do
add_data()
for k, _ in pairs(t) do
t[k] = nil
end
end
end
)
结果是创建新表的时间有三倍之多。