在递归函数中将大列表作为参数传递时的性能? [英] Performance when passing huge list as argument in recursive function?

查看:47
本文介绍了在递归函数中将大列表作为参数传递时的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 并且我有一个递归函数,它将一个巨大的列表作为参数之一:

I am using Python and I have a recursive function that takes a huge list as one of the arguments:

# Current implementation
def MyFunction(arg1, arg2, my_huge_list)
    ...
    ...
    MyFunction(new_arg1, new_arg2, my_huge_list)

如上所示,MyFunction 使用相同 列表my_huge_list 递归调用;与其他参数不同,这不会改变.而且,这个列表是巨大的.我的一个朋友建议我可以把 my_huge_list 当作一个全局变量来提高性能,否则这个庞大的列表可能会在每次迭代中一遍又一遍地复制.

As you can see above, MyFunction is called recursively using the same list my_huge_list; this doesn't change, unlike the other arguments. And, again, this list is huge. A friend of mine suggested that I could treat my_huge_list as a global variable to improve the performance, as otherwise this huge list may be copied over and over in every iteration.

# Friend's suggestion

MyHugeList=[a,b,c, ...and many many other elements... ]

def MyFunction(arg1, arg2)
    global MyHugeList
    ...
    ...
    MyFunction(new_arg1, new_arg2)

使用如上所示的全局变量是否比原始版本提高了算法的性能?我的程序运行了数周,所以从长远来看,即使是轻微的改进也可能是有价值的.

Does using a global variable as shown above improve the performance of the algorithm over the original version? My program runs for weeks, so even a slight improvement may be valuable in the long run.

推荐答案

列表将通过引用传递,因此不再需要传输 1 项列表与 100000 项列表:

The list will be passed by reference, so it doesn't take any longer to transfer a 1-item list vs. a 100000 item list:

def null(x): return x
longlist = range(100000)
shortlist = range(1)
longerlist = range(1000000)

%timeit null(shortlist)
10000000 loops, best of 3: 124 ns per loop

%timeit null(longlist)
10000000 loops, best of 3: 137 ns per loop

%timeit null(longerlist)
10000000 loops, best of 3: 125 ns per loop

较长的列表中有 100k 和 1M 的条目,但与较短的列表相比,作为参数传递的时间并不长.

The longer lists have 100k and 1M entries in them, and yet don't take significantly long to pass as arguments than shorter lists.

可能还有其他方法可以提高性能;这可能不是其中之一.

there may be other ways to improve performance; this probably isn't one of them.

这篇关于在递归函数中将大列表作为参数传递时的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆