[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-users] 2D array question





El 3 mar 2019, a las 4:34 PM, nick.colvin@xxxxxxxxx escribió:

Thanks everyone for the explanation, which more or less clears up the functional 'why' of my question. 

But I'm still a little confused. Tom, when you say 'pass-by-reference instead of pass-by-value', is that a property of the thing being passed, rather than the language itself?

I tried e.g. this:

x = 0; // or true/false/whatever value
y = Array.fill(8, x);
x = 1;
y.postln;// == [0,0,0,0,0,0,0]

but if I do:

x = [0];
y = Array.fill(8, x);
x[0] = 1;
y.postln; // == [[1],[1],[1],[1],[1],[1],[1],[1]];

So is it correct to understand that arrays are passed as a reference to the array, but unary value variables as the value of the variable? And if so, is there a reason for that?


Yes, exactly. Basically scalar values are passed by value, objects (incl. arrays) are passed by reference.  Lots of OO languages do this and it's sometimes a source of subtle bugs.

I think the reasoning is that it gives better performance - it's easier on RAM not to duplicate objects, which are typically larger, and when you've got a scalar it's "wasteful" to have indirection - for small scalars that fit in a machine word (bounded Int32s and Int64s, Bools), you use at least an extra machine word, and it slows down number-crunching code to dereference (which adds at least one instruction).

Not sure a language designed today would consider the savings worth the confusion (especially since numeric-heavy code isn't super-practical in sclang for other reasons), but it probably had a noticeable difference back in the day.

Tom


On Mon, Feb 25, 2019 at 4:12 PM <daniel-mayer@xxxxxxxx> wrote:
Besides of the already solved issue - which is fooling a lot of people - it's questionable if there's any advantage of using 2D arrays. The optimization is minimal, if there is one at all - there have been counter examples posted in the past, even the first help file example is faster with a nested array on my machine. IMO it's not worth having the quirk of being forced to think about an extra data type.

Regards

Daniel

-----------------------------
http://daniel-mayer.at
-----------------------------