Michel Fortin wrote:
On 2010-02-18 03:10:47 -0500, Don <[email protected]> said:
Well, array literals are not always constants. Take this for instance:
int[] array = [x, y, z];
This array literal does not have an "immutable source" as you call it.
This is the issue. The syntax sugar you get from not requiring an
"immutable source" comes at a very high price.
Should it really require a ".dup" to get a mutable array? How
efficient would it be?
What it does at the moment is insert a hidden .dup at all times. And
the performance is terrible. Really, really terrible. Roughly 100
times worse than you expect.
At the moment, [1, 2, 3] is basically transformed into something like
makeArray(1,2,3);
I agree the performance is terrible because of the often unnecessary
heap allocation.
It's not just the heap allocation. The values are also recalculated.
But assigning a literal to an immutable array should be
easy to special-case in the compiler so that it doesn't do an
unnecessary copy.
Yes, but that doesn't work in the general case. It cannot be done for
anonymous literals.
Also you can't force an array literal to be CTFEd.
Also, they're quite useful. How would you write the code above without
them?
int[] array;
array.length = 3;
array[0] = x;
array[1] = y;
array[2] = z;
Including the library implementation:
T[] toArray(T)(T[] values...)
{
return values.dup;
}
int[] array = toArray(x,y,z);
Mutable array literals achieve almost nothing.