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

Walter Bright newshound1 at digitalmars.com
Mon Apr 28 10:28:34 PDT 2008


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.



More information about the Digitalmars-d mailing list