References to variables

From Remeis-Wiki
Jump to navigation Jump to search

References to variables

(after an email by Manfred)

This should explain difference between modifying an array (which is passed by reference into functions) and creating a new array (whose scope is only local to your functions and will therefore be garbage-collected after the function has exited).

Whenever you modify only elements of an array a, i.e., when you use

a[where(a>2)] +=1;

or

a[*] +=1;

the reference to the array as a whole is not changed, which means that you really modify the original array.

Whenever you assign a new value to the entire variable `a', i.e. for

a += 1;

which is just an abbreviation for

a = a + 1;

or when you make an explict copy:

a = @a;

you lose the reference to the original array. It doesn't matter that your new value happens to again be an array, whose values are closely related to the original array...

Therefore, if you plan on modifying an array that was passed to the function through a qualifier, make sure you actually make a copy of the array

variable tim = @qualifier("tim",[0.,0.]);

such that changes are not passed on to the array outside the function. Otherwise, you might be in for an unpleasant surprise.

Dereferencing a reference to a variable or function (the qualifier function in this example) would be:

variable qref = &qualifier;
variable bla = (@qref)("tim",[0,0]);

The fact that reassigning entire arrays requires the creation of a new array, followed by -- if there are no further references to the original one -- garbage-collection of the old array (i.e. freeing its memory), is the reason why building up arrays in loops is, though convenient, so slow (for sufficiently large N) compared to building up lists, and should therefore be avoided:

variable a = Double_Type[0];
_for i (0, N)   a = [a, f(i)];  % creates a new

vs.

variable l = {};
_for i (0, N)   list_append(l, f(i));  % work on one list
variable a = list_to_array(l);

(If you're interested, see a crux:~hanke/array_copy for a live demo of the O(n^2) slowdown of `a=[a,f(i)]'.)