Python efficiency of and vs multiple ifs

后端 未结 5 872
太阳男子
太阳男子 2021-02-07 05:32

Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like

if expr1 == expr2 and         


        
5条回答
  •  不知归路
    2021-02-07 06:05

    The first one (one if with and) is faster :-)

    I tried it out using timeit. These are the results:

    Variant 1: 9.82836714316
    Variant 2: 9.83886494559
    Variant 1 (True): 9.66493159804
    Variant 2 (True): 10.0392633241
    

    For the last two, the first comparision is True, so the second one is skipped. Interesting results.


    import timeit
    
    
    print "Variant 1: %s" % timeit.timeit("""
    for i in xrange(1000):
        if i == 2*i and i == 3*i:
            pass
            """,
            number = 1000)
    
    print "Variant 2: %s" % timeit.timeit("""
    for i in xrange(1000):
        if i == 2*i:
            if i == 3*i:
                pass
            """,
            number = 1000)
    
    print "Variant 1 (True): %s" % timeit.timeit("""
    for i in xrange(1000):
        if i == i and i == 3*i:
            pass
            """,
            number = 1000)
    
    print "Variant 2 (True): %s" % timeit.timeit("""
    for i in xrange(1000):
        if i == i:
            if i == 3*i:
                pass
            """,
            number = 1000)
    

提交回复
热议问题