Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何/为什么通过将类属性复制到局部变量来优化代码?_Python_Oop_Optimization - Fatal编程技术网

Python 如何/为什么通过将类属性复制到局部变量来优化代码?

Python 如何/为什么通过将类属性复制到局部变量来优化代码?,python,oop,optimization,Python,Oop,Optimization,我有一个运行数值模拟的函数。主函数的输入太多,我创建了一个类(没有方法)来存储它们,类似于: myinput=MyInput() myinput.file1 = file1 myinput.file2 = file2 myinput.something = something run_model(myinput) 我认为优化代码的一种方法是创建局部变量,这样程序中的许多函数就可以读取局部变量,而无需访问MyInput类的对象。这是因为这些变量中的大多数都需要多次访问,我认为访问classins

我有一个运行数值模拟的函数。主函数的输入太多,我创建了一个类(没有方法)来存储它们,类似于:

myinput=MyInput()
myinput.file1 = file1
myinput.file2 = file2
myinput.something = something
run_model(myinput)
我认为优化代码的一种方法是创建局部变量,这样程序中的许多函数就可以读取局部变量,而无需访问MyInput类的对象。这是因为这些变量中的大多数都需要多次访问,我认为访问classinstance.attribute而不是localvariable是有代价的。例如:

def myfun(myinput):
    something=myinput.something
    step1=fun1(something)
    step2=fun2(something)
    out=something + step1 + step2
这种推理正确吗? 我已经用下面的代码对它进行了测试,我看到了大约30%的改进。是否有其他改进方法?这是预期的吗?在开始重构我所有的代码之前,我想了解它背后的理论

为什么访问myclass.attributes的性能代价如此高昂?这是Python的一个限制,还是其他语言也有这种情况

import timeit

class MyClass:
    def __init__(self,a,b,c,d,e):
        self.a=a
        self.b=b
        self.c=c
        self.d=d
        self.e=e

def fun_local(myclass, size):
    a=myclass.a
    b=myclass.b
    c=myclass.c
    d=myclass.d
    e=myclass.e

    for i in range(size):
        x = (a+b)**c+d*e

def fun(myclass, size):
    for i in range(size):
        x= (myclass.a + myclass.b)** myclass.c + myclass.d * myclass.e

myclass=MyClass(8,4,4,10,100)
rep=3
num=10
size=int(1e6)
res_local = min( timeit.Timer( "fun_local(myclass, size)", globals=globals() ).repeat(repeat= rep, number = num )   )
res_noloc = min( timeit.Timer( "fun(myclass, size)", globals=globals() ).repeat(repeat= rep, number = num )   )

它更快,因为将值绑定到局部变量意味着可以更快地找到它-查找过程可能非常耗时,因此如果您创建一个存储在选中的第一个位置的名称,则可以更快地找到它。看,谢谢。我会看到类似C语言的30%速度改进,比如C++语言,C++语言?Compiled coded在运行时不进行变量名查找。它更快,因为将值绑定到局部变量意味着可以更快地找到它-查找过程可能非常耗时,因此如果您创建的名称存储在选中的第一个位置,则可以更快地找到它。看,谢谢。我会看到类似C语言的30%速度改进,比如C++语言,C++语言?编译代码在运行时不进行变量名查找。