python - 在 Python 函数中使用大数据结构时的效率

标签 python pass-by-reference function-call

我需要使用一个大数据结构,更具体地说,一个大字典来完成查找工作。

一开始我的代码是这样的:

#build the dictionary
blablabla
#look up some information in the ditionary
blablabla

由于我需要多次查找,我开始意识到将其实现为一个函数是个好主意,比如 lookup(info)

那么问题来了,大字典应该怎么处理呢?

我应该使用 lookup(info, dictionary) 将其作为参数传递,还是应该在 main() 中初始化字典并将其用作全局变量?

第一个似乎更优雅,因为我认为维护全局变量很麻烦。 但另一方面,我不确定将大字典传递给函数的效率。它会被调用很多次,如果参数传递效率低下,那肯定会是一场噩梦。

谢谢。

编辑1:

我只是对以上两种方式进行了实验:

这是代码片段。 lookup1 实现传递查找的参数,而 lookup2 使用全局数据结构“big_dict”。

class CityDict():
    def __init__():
        self.code_dict = get_code_dict()
    def get_city(city):
        try:
            return self.code_dict[city]
        except Exception:
            return None         

def get_code_dict():
    # initiate code dictionary from file
    return code_dict

def lookup1(city, city_code_dict):
    try:
        return city_code_dict[city]
    except Exception:
        return None

def lookup2(city):
    try:
        return big_dict[city]
    except Exception:
        return None


t = time.time()
d = get_code_dict()
for i in range(0, 1000000):
    lookup1(random.randint(0, 10000), d)

print "lookup1 is %f" % (time.time() - t)


t = time.time()
big_dict = get_code_dict()
for i in range(0, 1000000):
    lookup2(random.randint(0, 1000))
print "lookup2 is %f" % (time.time() - t)


t = time.time()
cd = CityDict() 
for i in range(0, 1000000):
    cd.get_city(str(i))
print "class is %f" % (time.time() - t)

这是输出:

lookup1 is 8.410885
lookup2 is 8.157661
class is 4.525721

所以看起来这两种方式几乎是一样的,是的,全局变量的方法效率更高一点。

编辑2:

添加了Amber建议的class版本,然后再测试效率。那么从结果可以看出Amber是对的,我们应该使用class版本。

最佳答案

回答核心问题,参数传递并不是低效的,它不会像您的值一样被复制。 Python 传递引用,这并不是说传递参数的方式符合众所周知的“按值传递”或“按引用传递”方案。

最好将其想象为使用调用者提供的引用值来初始化被调用函数的局部变量值,这些值是按值传递的。

不过,使用类的建议可能是个好主意。

关于python - 在 Python 函数中使用大数据结构时的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665461/

相关文章:

python - 如何使用 python 3 让数据沿线显示?

python - 禁止通过 swig 为 python-C++ 接口(interface)生成隐式类型检查代码

python - 从坏词列表创建审查函数

php - 数组循环改变元素类型

Python垂直数组切片

objective-c - 从方法返回 2 个结果的最佳方法是什么

c++ - 在 C++ 中通过引用传递可选参数

计算可执行文件中的函数调用次数

c - 函数原型(prototype)和 block 代码 : difference? 中的变量声明

c - 这段 C 代码中该函数被调用了多少次?