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. 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. In fact, forcing literals to be assigned to immutable arrays only is the same special case, except it disallows the other case where it needs to do a copy (assigning to mutable).

Non-constant array literals can also be optimized in some situations: when they don't escape the function's scope, they can be allocated on the stack. Better optimization could take advantage of that.

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;

Not very attractive isn't it? And it wouldn't work when assigning to an array of immutable(int)[]. Also, I expect this'll make it harder for the compiler to optimize and allocate on the stack when it can.


--
Michel Fortin
[email protected]
http://michelf.com/

Reply via email to