While 1比While True快?
# python 2.0
import timeit
def while_one():
i = 0
while 1:
i += 1
if i == 10000000:
break
def while_true():
i = 0
while True:
i += 1
if i == 10000000:
break
if __name__ == "__main__":
w1 = timeit.timeit(while_one, "from __main__ import while_one", number=3)
wt = timeit.timeit(while_true, "from __main__ import while_true", number=3)
print "while one: %s\nwhile_true: %s" % (w1, wt)
Execution result:
while one: 1.37000703812
while_true: 2.07638716698
In fact, this is the problem of keywords mentioned in the premise. Since in Python2, True/False is not a keyword, we can assign any value to it, which causes the program to check the value of True/False every time it loops; and for 1, it is performed by the program Optimized, and then will not be checked again.
In Python3, since True/False is already a keyword, reassignment is not allowed, so the execution result is no longer different from while 1 (well, I don’t have a Python3 environment, so I won’t verify it. Someone on the Internet has verified it). But because Python2 is widely used, everyone has to pay attention to this place that may reduce performance.
if x == True: or if x
Regardless of following the PEP specification, execution efficiency, or program simplicity, we should use if x: instead of if x == True: for comparison. In the same way, statements such as if x is not None: should also be simplified to if x: (if the comparison is not a value, it does not have to be None).