xxxInPlace or xxxCopy?

Jonathan M Davis jmdavisProg at gmx.com
Wed Jan 19 17:39:34 PST 2011


On Wednesday, January 19, 2011 17:10:07 Andrei Alexandrescu wrote:
> On 1/19/11 6:53 PM, Jonathan M Davis wrote:
> > On Wednesday, January 19, 2011 15:33:16 Andrei Alexandrescu wrote:
> >> I'm consolidating some routines from std.string into std.array. They are
> >> specialized for operating on arrays, and include the likes of insert,
> >> remove, replace.
> >> 
> >> One question is whether operations should be performed in place or on a
> >> copy. For example:
> >> 
> >> string s = "Mary has a lil lamb.";
> >> // Implicit copy
> >> auto s1 = replace(s, "lil", "li'l");
> >> assert(s == "Mary has a lil lamb.");
> >> // Explicit in-place
> >> replaceInPlace(s, "lil", "li'l");
> >> assert(s == "Mary has a li'l lamb.");
> > 
> > ++vote;
> > 
> >> So that would make copying the default behavior. Alternatively, we could
> >> make in-place the default behavior and ask for the Copy suffix:
> >> 
> >> string s = "Mary has a lil lamb.";
> >> // Explicit copy
> >> auto s1 = replaceCopy(s, "lil", "li'l");
> >> assert(s == "Mary has a lil lamb.");
> >> // Implicit in-place
> >> replace(s, "lil", "li'l");
> >> assert(s == "Mary has a li'l lamb.");
> > 
> > --vote;
> 
> So I guess vote stays unchanged :o).
> 
> >> Thoughts?
> > 
> > Haven't we been using the approach that string operations generally make
> > copies (in many cases slices) and marking functions that do it in place
> > with InPlace?
> 
> Problem is, even though the example uses strings, the functions apply to
> all arrays.

True. But I would expect a string to be by far the most used type of array. So, 
unless you want to specialize the functions so that they work one way for 
strings and another way for other arrays (which sounds like a really bad idea), 
it would make the most sense to pick the way that's most likely to be used as 
the default. And since strings are the most likely case, choosing what works 
best for strings seems like the best idea IMHO.

And honestly, from the standpoint of code simplicity and understandability, 
there's a lot to be said for making copies being the default rather than 
mutation. You can then use the InPlace versions if you need the boost in 
efficiency.

- Jonathan M Davis


More information about the Digitalmars-d mailing list