[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: efficient function parameter copying?
From: |
Michael Pronath |
Subject: |
Re: efficient function parameter copying? |
Date: |
Fri, 10 Sep 1999 19:28:29 +0200 |
address@hidden said:
> Octave values are implemented using reference-counted objects. The
> data is not duplicated unless it is necessary. So, for something like
> function y = f (x)
> y = x;
> endfunction
> w = f (z);
> only one copy of z should actually exist (but the reference count will
> be incremented and decremented as necessary).
> For something like
> function y = f (x)
> y = x;
> y(some_index) = some_value; # or some other way of modifying y
> endfunction
> however, a copy of x will be made when y is modified.
yes, that's what I thought, too. But in your example definitions, it's
function y=f(x), while I meant function x=f(x). And you call it with
w=f(z), while I meant z=f(z). This is an important difference, as in
my case, the formal input and output parameters are the same plus the
actual input and output parameters are the same. Of course, my function
performs changes on x, else it would be without any effect.
If octave uses reference-counted objects without any further optimization,
the complete matrix will be copied for every call to f unnecessarily.
Take for an example
X=eye(500,500);
for i=1:1000
X=iterate(X);
endfor
and
function M = iterate(M)
M(1,1) = M(1,1)+3*M(2,2);
M(2,2) = -M(1,1); %% could do something useful here as well
endfunction
Is there a need to copy the 500x500 matrix 2000 times? Certainly not,
and I wanted to know if octave can detect this and avoid the copying.
If not, it is better to write
global X;
X=eye(500,500);
for i=1:1000
iterate();
endfor
and
function iterate()
global X;
X(1,1) = X(1,1)+3*X(2,2);
X(2,2) = -X(1,1); %% could do something useful here as well
endfunction
which is not quite what I want to do.
This optimization could be simply done by taking the names of the
actual parameters and the formal parameters of a function call and
searching for "matching pairs". This could make a true "call by
reference" possible.
Michael
---------------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL. To ensure
that development continues, see www.che.wisc.edu/octave/giftform.html
Instructions for unsubscribing: www.che.wisc.edu/octave/archive.html
---------------------------------------------------------------------