Invariant strings on Dr. Dobb's

Sean Kelly sean at invisibleduck.org
Fri Mar 14 11:15:28 PDT 2008


== Quote from BCS (ao at pathlink.com)'s article
> Reply to Walter,
> > Dr. Dobb's has invited me to write a blog for them, so here's my first
> > installment on invariant strings:
> >
> > http://www.dobbscodetalk.com/index.php?option=com_myblog&show=Invarian
> > t-Strings.html&Itemid=29
> >
> wow, a publicly available picture of Walter!
> And on the content; you mention concatenation as working on invariant strings.
> I assume this is because you generally can't concatenate in place anyway?

Regarding D specifically, I think it is generally quite possible to append to a string in place, but doing so
can be problematic for the inattentive programmer:

    char[] refA = "abc".dup;
    char[] refB = refA;
    refA ~= "def";
    refB ~= "ghi";

With mutable strings, the above will likely result (depending on the runtime and GC implementation) in
both refA and refB still pointing to the same location, which contains"abcghi".  Invariant strings address
this issue by providing predictable semantics, making strings behave very much like a value type.  This is
achieved through always reallocating and copying when a mutation occurs however, which I feel makes
it not suitable for all situations.  It's a great default for everyday programming, but must be used much
more carefully in performance-critical applications.  So in short, I'm not convinced that invariant strings
will save the world--at least not until we have zero-cost garbage collection--but they are certainly
quite easy and safe to use.


Sean


More information about the Digitalmars-d-announce mailing list