结论
对象式调用比函数式调用要快0.2%左右,
对象式调用比反射式调用要快82%左右,
函数式调用比反射式调用快79%左右。
(采用的算法为(a-b)/b
,其中a
>b
,b
为"比较对象
",a
为"被比较对象
")
环境
- python 3.11.5
- win10x64-22H2
- IDE: pycharm-comunity
- cpu: i5-10200H
用例代码(分块)
用例对象
class clss:
def fun():
...
定义测试运行次数
times = 10000000
用例初始化
classes = [clss() for i in range(times)]
对象式调用
for c in classes:
c.fun()
函数式调用
f = c.fun
for c in classes:
f(c)
反射式调用
fn = c.fun.__name__
for c in classes:
c.__getattribute__(fn)()
用例代码(完整)
class clss:
def fun():
...
times = 10000000
classes = [clss() for i in range(times)]
t = time.time()
for c in classes:
c.fun()
print("对象式",time.time-t)
t = time.time()
f = c.fun
for c in classes:
f(c)
print("函数式",time.time-t)
t = time.time()
fn = c.fun.__name__
for c in classes:
c.__getattribute__(fn)()
print("反射式",time.time-t)