Skip to main content
 首页 » 编程设计

python之为什么方法这么慢

2025年05月04日12lyhabc

好的,我理解像 C++ 这样的语言,为什么调用类中定义的虚拟方法比调用非虚拟方法慢(您必须通过动态调度表来查找要调用的正确实现)。

但是在 Python 中,如果我有:

list_of_sets = generate_a_list_containg_a_bunch_of_sets() 
intersection_of_all = reduce(list_of_sets[0].intersection, list_of_sets) 

这显着(在我的实验中大约慢了 40%):

list_of_sets = generate_a_list_containg_a_bunch_of_sets() 
intersection_of_all = reduce(set.intersection, list_of_sets) 

我不明白的是为什么它应该慢得多,方法查找(我认为)会在调用 reduce 时发生,所以 reduce 内部实际调用交集方法的地方不应该有再次查找(它只是重复使用相同的方法引用)。

有人可以指出我的理解有缺陷吗?

请您参考如下方法:

这与方法绑定(bind)等完全无关。第一个版本在每次迭代中计算三个集合的交集,而第二个版本只计算两个集合的交集。如果我们改用显式循环,这一点很容易看出。

变体 1:

intersection = list_of_sets[0] 
for s in list_of_sets[1:]: 
    intersection = list_of_sets[0].intersection(intersection, s) 

变体 2:

intersection = list_of_sets[0] 
for s in list_of_sets[1:]: 
    intersection = set.intersection(intersection, s) 

(您现在是否同意 Guido 的观点?)

请注意,这可能会更快:

intersection = list_of_sets[0] 
for s in list_of_sets[1:]: 
    intersection.intersection_update(s)