我有一个包含属性的类(假设类文件的名称是 inputvar
),
我将它用作两个不同函数的输入参数,这两个函数的计算完全相同,但代码略有不同,稍后我将对此进行解释。
对于第一个函数(假设名称是 myfun1),我这样写输入参数:
f = myfun1 (inputvar)
所以每次我想在函数内部使用类中的变量时,我都必须调用 inputvar.var1
、inputvar.var2
等
对于第二个函数 (myfun2),我在输入参数中写入了类中的每个变量,所以它看起来像这样:
f = myfun2 (inputvar.var1, inputvar.var2, ...等)
在函数内部,我只需使用 var1
、var2
等,而无需包含类名。
运行两个函数后,我发现myfun2
运行速度比myfun1
快很多,大约60%(我用的是tic-toc)。
谁能给我解释一下这是为什么?
最佳答案
与 reference :
MATLAB uses a system commonly called "copy-on-write" to avoid making a copy of the input argument inside the function workspace until or unless you modify the input argument. If you do not modify the input argument, MATLAB will avoid making a copy. For instance, in this code:
function y = functionOfLargeMatrix(x) y = x(1); MATLAB will not make a copy of the input in the workspace of functionOfLargeMatrix, as x is not being changed in that function. If on the other hand, you called this function:
function y = functionOfLargeMatrix2(x) x(2) = 2; y = x(1); then x is being modified inside the workspace of functionOfLargeMatrix2, and so a copy must be made.
根据上面的说法,当您直接传递一个类对象并更改该对象的任何成员时,将应用该类的整个复制操作。
另一方面,通过将类成员作为单独的参数,复制操作仅适用于函数中修改的相关成员,从而加快执行速度。
关于通过引用传递的 MATLAB 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17932396/