Array literals MUST be immutable.

Denis Koroskin 2korden at gmail.com
Thu Feb 18 13:17:50 PST 2010


On Thu, 18 Feb 2010 18:42:16 +0300, Michel Fortin
<michel.fortin at michelf.com> wrote:

> On 2010-02-18 08:00:55 -0500, Don <nospam at nospam.com> said:
>
>>> 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.
>
> Well, in the case of a constant literal expression they don't need to be  
> recalculated, they could exist in the static data segment. If a constant  
> array literal is assigned to an immutable array they don't even need to  
> be copied. I trust the compiler will eventually do that (and sooner the  
> better).
>
>
>>> 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.
>
> I'm not sure what you mean by "anonymous literals". Aren't all literals  
> anonymous?
>
>
>> Also you can't force an array literal to be CTFEd.
>
> I think that's a more general problem with CTFE. But you can force CTFE  
> using an enum:
>
> 	enum value = ctfeFunction();
>
> Wrap that in a template if you want more convenience:
>
> 	template ctfe(alias ctfeValue) {
> 		enum ctfe = ctfeValue;
> 	}
>
> 	auto variable = ctfe!(ctfeFunction());
>
>
>>> 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.
>
> But now, how can the compiler optimize this and stack-allocate your  
> array when it detect doesn't escape your function? You're explicitly  
> telling it to duplicate it, even the compiler could decide it's not  
> necessary. (I know stack-allocation isn't implemented, but Walter said  
> it could be done.)
>
> Consider this case:
>
> 	int a, b, c;
> 	int[] array;
> 	array ~= [a, b, c];
> 	array ~= toArray(a, b, c);
>
> Does it make sense to heap-allocate the mutable array? Hardly. With the  
> literal, the compiler is free to optimize away the heap allocation, not  
> so with toArray.
>
>

[a, b, c] could result in a static array. Then there wouldn't even be a  
need for toArray, just use more natural int[] arr = [a, b, c].dup; syntax



More information about the Digitalmars-d mailing list