Const, invariant, strings and "constant data need never be copied"

Walter Bright newshound1 at digitalmars.com
Fri Nov 2 21:47:01 PDT 2007


Stewart Gordon wrote:
> Note that the text is never copied after it is read in, except by 
> std.string.replace if it actually makes any change.  In D 2.x, it's 
> necessary to change one line, to something like
> 
>    text = text.idup.replace("\r\n", "\n").replace("\r", "\n").dup;
> 
> which consequently adds two copy operations.

Well, no. Take a look at the source to std.string.replace(). It does not 
modify the input in place - it returns the input if there are no 
changes, if there are changes, it returns a *copy*. Second, text should 
be declared as a string, so you do not need either of the dup's. Two 
copies are made, just as with the 1.0 version, in that line of code.

You will need a third copy to do the loop which modifies the string in 
place. I feel that, with strings, the advantages of invariant strings 
outweigh the disadvantages.

Note that one can still do the modify-in-place D 1.0 code, and do it 
very fast, by putting the tests for \r inside the loop rather than as 
separate loops. The D 1.0 version isn't what you'd write if you wanted 
speed, anyway.



More information about the Digitalmars-d mailing list