1. 局部变量优于全局变量
2. 使用 . 调用不如直接导入或赋值,每次使用.
(属性访问操作符时)会触发特定的方法,如__getattribute__()
和__getattr__()
import math # 1
# from math import sqrt # 2
import datetime
# 耗时: 25.813275
start = datetime.datetime.now()
size = 10000
for x in range(size):
for y in range(size):
z = math.sqrt(x) + math.sqrt(y)
end = datetime.datetime.now()
print(end - start)
def main():
# 1. math.sqrt: 22.187628
# 2. from math import sqrt, sqrt: 18.627520
# 3. sqrt = math.sqrt 局部变量赋值: 17.320667
size = 10000
sqrt = math.sqrt # 3
start = datetime.datetime.now()
for x in range(size):
for y in range(size):
z = sqrt(x) + sqrt(y)
end = datetime.datetime.now()
print(end - start)
3. 使用 if 短路特性,配合 and or 使用
4. for 循环优于 while 循环,因为每次循环中, while
实际上比 for
多执行了两步操作:边界检查和变量 i
的自增。
def while_loop(n=100_000_000):
i = 0
s = 0
while i < n:
s += i
i += 1
return s
def for_loop(n=100_000_000):
s = 0
for i in range(n):
s += i
return s
def main():
print('while loop\t\t', timeit.timeit(while_loop, number=1))
print('for loop\t\t', timeit.timeit(for_loop, number=1))
if __name__ == '__main__':
main()
# => while loop 4.718853999860585
# => for loop 3.211570399813354
5. 多层 for 循环时,减少外层 for 循环层数,遵循 外小内大原则。自己测试差距很小,甚至没有
6. 交互变量无需中间临时变量,a, b = b, a
7. 字符串相加使用 join 而不是 +