Lua一些容易被忽视的性能问题

分支判断条件为字符串,查表与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
)

结果是创建新表的时间有三倍之多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值