为什么Lua中error()比assert()更快?

断言条件是一种以_strategic方式_设计应用程序的公认方法。你可以完全确定你的代码在发布后一天或者其他团队中的其他开发人员更改代码时将正确工作。

在Lua代码中放置断言有两种常见的方法:

assert(1 > 0, "断言数学是正确的")
if 1 <= 0 then
    error("断言数学是不正确的")
end

从性能角度来看,我希望这个事情是一样的。只考虑样式问题。但实际上并不是这样。

assert在我的电脑上工作时间更长:

function with_assert()
    for i=1,100000 do
        assert(1 < 0, '断言')
    end
end

function with_error()
    for i=1,100000 do
        if 1 > 0 then
            error('错误')
        end
    end
end

local t = os.clock()
pcall(with_assert)
print(os.clock() - t)

t = os.clock()
pcall(with_error)
print(os.clock() - t)

> 3.1999999999999e-05

> 1.5e-05

为什么会出现这种情况呢?

点赞
用户107090
用户107090

查看 asserterror 的源代码: assert 做了一些工作,然后调用了 error

但是你代码中的循环没有任何作用:在第一次循环期间抛出错误意味着其余的迭代都不会运行。也许你的意思是将循环放在 pcalls 周围,如下所示。然后你会发现两种方法之间几乎没有任何区别。

function with_assert()
    assert(1 < 0, 'Assert')
end

function with_error()
    if 1 > 0 then
        error('Error')
    end
end

function test(f)
    local t = os.clock()
        for i=1,100000 do
            pcall(f)
        end
    print(os.clock() - t)
end

test(with_assert)
test(with_error)
2020-05-14 11:47:00