5

Matlab 的传值调用的效率问题

 3 years ago
source link: https://zhiqiang.org/coding/call-by-value-or-reference-in-matlab.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Matlab 的传值调用的效率问题

作者: 张志强

, 发表于 2010-09-21

, 共 1315 字 , 共阅读 130 次

本文结论:不要过度担心 Matlab 的传值调用的效率问题。

刚学 Matlab 的时候便被告诉 Matlab 的函数的参数都是通过传值调用( call by value ),它的特点是在函数内部对于参数的修改不会影响外面的值。

传值调用参数时,函数内部复制了参数的一份副本。在大多数情况下,这种复制操作的消耗很小,但如果参数对象很大的话(比如为一个 1000×1000 的矩阵),这样的操作会大大降低函数运行的效率,增加函数调用占用的内存(复制一份对象需要增加使用 80M 内存)。

幸运的是, Matlab 对此进行了优化,如果该参数在函数内部没有被修改,那么在实现时,它实质上用的是传引用调用( call by reference )

http://www.mathworks.com/support/solutions/en/data/1-15SO4/index.html?solution=1-15SO4

For MATLAB built-in data types, MATLAB always passes arguments 'by value' in the sense that any changes made to input arguments within a function are not visible to the respective variables in the caller workspace.

However, since passing huge chunks of data 'by value' is inefficient, MATLAB internally optimizes for some cases and passes by reference and only creates local copies if modifications are being made to these arguments.

可测试下面的 test 函数:

function a = test(m, t)

if t > 0
    if t == 0
        m(1, t) = t;
    end
    m = subtest(m);
    a = test(m, t-1) + 1;
else
    a = 1;
end

function a = subtest(m)
a = m;

比如测试 test(rand(1000), 200)。如果函数是使用传值调用,那么它早就奔溃了(因为在 200 次递归中共需要 80M×200=16G 内存)。但实际测试中,程序能在 1 秒钟内给出结果,内存占用也很少。事实上,在程序实际运行的过程中使用的是传引用调用的方式。

更进一步地说,Matlab 在程序运行过程中而不是编译的时候(或者刚进入函数的时候)确定用哪种方式调用参数。所以即使发生了赋值操作,只要赋值不修改变量的值(比如 a=a 这样的赋值), Matlab 不会生成副本。只有在变量的值被实质修改时,程序才会生成一个临时副本。

Q. E. D.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK