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

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 28 07:32:08 PDT 2008


"Janice Caron" wrote
> 2008/4/28 Steven Schveighoffer:
>>  > I have some strings read in from external source that I need to 
>> convert to
>>  > uppercase. A quick look at Phobos and I find std.string has a toupper
>>  > method.
>>  > <very good example case removed>
>>
>>  This is all not an issue if Walter adopts 'scoped const' contracts.
>
> toupper() couldn't be reused for all constancies, because the
> invariant version should employ copy-on-write, wheras any other
> versions would not be able to do this.
>
> That is,
>
>    toupper("HELLO");
>
> can return the original, if and only if the string is invariant.

toupper is probably a bad example, as your case seems like the rarest :) 
But I understand what you are saying.

The desire to have string processing functions work with all constancies 
seems very reasonable and useful to me.  To deny usage of toupper unless you 
idup the array, just to have the ability to optimize on a corner case seems 
incorrect, and to probably produce less efficient code for 90% of the cases. 
If the scoped const proposal was never accepted, and I used Phobos, I'd 
probably suggest a const and mutable version of toupper that allowed for 
those of us who use mutable strings a lot, and maybe not so much 
multithreadding, to not have to jump through hoops for any string 
processing.

Maybe the solution to this is to write specializations which use COW with 
the invariant version, perhaps with pure functions, which always assume 
invariant parameters.  So you have a pure toupper which handles the 
invariant version, and a scoped const version which allows using the 
function on non-invariant parameters, which can't be optimized the same 
anyways...

-Steve 





More information about the Digitalmars-d mailing list