python Python EAFP与LBYL的速度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python EAFP与LBYL的速度相关的知识,希望对你有一定的参考价值。

import reusables


@reusables.time_it()
def test_lbyl(messages):
    out = []
    for _ in range(10000):
        if messages and messages[0] and len(messages[0]) >= 3:
            out.append(messages[0][2])
    return out

@reusables.time_it()
def test_eafp(messages):
    out = []
    for _ in range(10000):
        try:
            out.append(messages[0][2])
        except IndexError:
            pass
    return out

if __name__ == '__main__':
    messages = [["hi there", "how are you?"]]
    assert len(test_lbyl(messages)) == len(test_eafp(messages))

    messages[0].append("I'm doing fine")
    assert len(test_lbyl(messages)) == len(test_eafp(messages))

    # LBYL is faster if the list isn't long enough, avoid an error and an attmepted append statement
    # Function 'test_lbyl' took a total of 0.0016206308322832311 seconds - args: ([['hi there', 'how are you?']],)
    # Function 'test_eafp' took a total of 0.0030271251617317893 seconds - args: ([['hi there', 'how are you?']],)
    
    # EAFP is faster when the success path is more common, avoiding the costly lookups  
    # Function 'test_lbyl' took a total of 0.0027111909965087614 seconds - args: ([['hi there', 'how are you?', "I'm doing fine"]],)
    # Function 'test_eafp' took a total of 0.001411011977187686 seconds - args: ([['hi there', 'how are you?', "I'm doing fine"]],)


以上是关于python Python EAFP与LBYL的速度的主要内容,如果未能解决你的问题,请参考以下文章

为什么在Python中“更容易请求宽恕而不是获得权限”?

Python中的EAFP原理是啥?

不就是Java吗之 认识异常

盘点Java中遇到的异常

21张让你代码能力突飞猛进的速查表(神经网络线性代数可视化等)

可能是史上最全的机器学习和Python(包括数学)速查表