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

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 28 11:36:45 PDT 2008


"Walter Bright" wrote
> p9e883002 at sneakemail.com wrote:
>> 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?
>
> You bring up a good point.
>
> On a tiny example such as yours, where you can see everything that is 
> going on at a glance, such as where strings come from and where they are 
> going, there isn't any point to immutable strings. You're right about 
> that.
>
> The problems start happening as the complexity rises. Strings get passed 
> around, stored, modified, etc. It's real easy to lose track of who owns a 
> string, who else has references to the string, who has rights to change 
> the string and who doesn't.
>
> For example, you're changing the char[][] passed in to main(). What if one 
> of those strings is a literal in the read-only data section?
>
> So what happens is code starts defensively making copies of the string 
> "just in case." I'll argue that in a complex program, you'll actually wind 
> up making far more copies than you will with invariant strings.

I agree that immutable strings can be valuable.  That's why I think it's 
important to have a version of toupper that uses invariant strings because 
you can make more assumptions about when to make copies.  But why shouldn't 
there be a version that does the same thing with mutable or const strings? 
Why should a developer be forced to always use invariant strings when the 
optimizations and multithreading benefits that come with only using 
invariant strings may not be more important for a particular program than 
being able to modify a string?  I should still be able to use toupper on 
mutable strings as well...

-Steve 





More information about the Digitalmars-d mailing list