Is all this Invarient **** er... stuff, premature optimisation?

Bill Baxter dnewsgroup at billbaxter.com
Sun Apr 27 17:33:30 PDT 2008


Simen Kjaeraas wrote:
> <p9e883002 at sneakemail.com> wrote:
> 
>> Of course, a wasn't really mutated. Instead, args[0] was copied and then
>> mutated and labelled a. Then a was copied and mutated and reassigned the
>> mutated copy.
>>
>> So, that's two copies of the string, plus a slice, plus an extra 
>> method call to
>> achieve what used to be achievable in place on the original string. 
>> Which is now
>> immutable, but I'll never need it again.
>>
>> Of course, on these short 1-off strings it doesn't matter a hoot. But 
>> when the
>> strings are 200 to 500 characters a pop and there are 20,000,000 of 
>> them. It
>> matters.
>>
>> Did I suggest this was an optimisation?
>>
>> Whatever immutability-purity cool aid you've been drinking, please go 
>> back to
>> coke. And give us usable libraries and sensible implicit conversions. 
>> Cos this sucks
>> bigtime.
>>
>> b.
> 
> 
> Is this what you wanted to write?
> 
> int main(string[] args)
> {
>   char[] a = cast(char[])args[0];
>   a[2..5] = "XXX";
>   writefln(a);
>   return 0;
> }
> This compiles and runs, and seems to do what you describe. Sure, there's a
> cast there, but it's not all that bad, is it?

I'm no invariant guru, but I don't think that's legal.  'invariant' 
means the data could be stored in a portion of memory that the OS will 
not allow the program to write to.  So you need to dup it:

    char[] a = args[0].dup;
    a[2..5] = "XXX";
    writefln(a);
    return 0;

That stuff like this compiles and seems to work is why we really need to 
make at least one alternative version of cast.  One would be for 
relative safe run-of-the-mill casts, like casting float to int, or 
casting Object to some class (and checking for null),  and the other 
category would be for dangerous big red flags kind of things like the 
above.  Using the run-of-the-mill cast in the above situation would not 
be allowed.

--bb



More information about the Digitalmars-d mailing list