www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Array literals MUST be immutable.

Don Wrote:

 This is for me the last remaining D2 issue.
 I've mentioned this several times before. Mutable array 'literals' are 
 wrong on so many levels. Here are some of the issues, listed in 
 decreasing importance.
 (1) The language has no syntax for immutable array literals.
    [1,2,3] is mutable. You can created an immutable literal using the 
 awful 'static const' syntax, but that only works for named literals.
 (2) Concurrency issues make (1) even more important. It ought to 
 possible to pass an array (defined at compile time) as a message.
 (3) Performance of the existing array 'literals' is absolutely 
 appalling. I doubled the speed of my entire app by changing ONE array 
 declaration from 'immutable [] xxx' into 'static const [] xxx'!!!
 Right now, if an array literal appears in your code, chances are it's a 
 performance bug. It's deceptive that there's a hidden heap allocation 
 happening in every array literal. It's got no business being in a 
 systems language IMHO.
 (4) It is unintuitive. "hello" is immutable, but ['h','e','l','l','o'] 
 is not???
 (5) It's trivial (a one-liner) to make a function to create a mutable 
 array literal. We don't need it in the language.
 Mutable arrays literals are common in toy examples, but they've got very 
 little real-world relevance. By contrast, immutable array literals are 
 used in lookup tables all the time. They are extremely common. We need 
 to be able to express them.
 This is the only remaining thing in D2 which I'm certain is a big 
 mistake. Of course there's ugliness in various places, but it's possible 
 to ignore them or work around them. This is a primitive, 
 bread-and-butter issue with no workaround.

I agree. This has caused huge performance problems that were fixed by changing all my 'immutable x = []' to 'static immutable x = []'. Can we keep the current behaviour for when some of the values are not known at compile time? I know it's just sugar but it's very sweet. eg. auto y = [1, 2, x, y];
Feb 18 2010