Const, invariant, strings and "constant data need never be copied"
Stewart Gordon
smjg_1998 at yahoo.com
Sat Nov 3 06:10:10 PDT 2007
"Walter Bright" <newshound1 at digitalmars.com> wrote in message
news:fgguis$1hsk$1 at digitalmars.com...
> 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*.
That's basically what I said.
> 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.
In the first of these two paragraphs, you suggest omitting the final .dup,
and then in the next, you effectively tell me to put it back in. Therein
lies my point - the "third copy" ought not to be necessary for my ad hoc
code. (I know I could cast away the invariant, but that's a rather down and
dirty trick.)
> I feel that, with strings, the advantages of invariant strings outweigh
> the disadvantages.
When it comes to string manipulation functions, giving the programmer the
choice, with my proposal of const-transparency, would AISI bring even more
advantages and alleviate some of 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.
Yes, that's another way to do it....
Stewart.
--
My e-mail address is valid but not my primary mailbox. Please keep replies
on the 'group where everybody may benefit.
More information about the Digitalmars-d
mailing list