COW vs. in-place.

Dave Dave_member at pathlink.com
Thu Aug 3 13:24:22 PDT 2006


Oskar Linde wrote:
> 
> 1. in-place default, copying algorithms specially named
> -------------------------------------------------------
> 
> Design:
> void toUpper(char[] str); // in-place
> char[] toUpperCopy(char[] str); // copy
> 
> Pros:
> * in-place is often more efficient and therefore default.
> * many functions are imperative verbs, and as such one expects them to 
> be modifying
> * Similar to how the C++ STL is designed
> Cons:
> * many functions can not be expressed in-place (example: UTF-8 toUpper)
> 

Hmmm - Is the current implementation of std.string.toupper wrong then?

(If you removed the if(!changed) {...} blocks [where the CoW is milked] you would effectively have 
an in-place implementation).

> 
> 2. copying default, in-place versions specially named
> -----------------------------------------------------
> 
> Design:
> void toUpperInPlace(char[] str); // in-place
> char[] toUpper(char[] str); // copy
> 
> Pros:
> * copying is safer, and is therefore a better default

Only if the coder expects that is the default, *and* they most often need the original data intact 
later in the program.

And that safety is not much of an advantage when your code is three-legged dog slow and eats up 
resources that could be used by other processes :) Walking to work may be safer than going 70 MPH on 
the freeway, but it would take me a week and I'd starve.

> * in-place is an optimization and would stand out as such

It's only considered an 'optimization' right now because it's different from the default (CoW).

> * default is functional (no-side effects), side effects stand out
> * people used to functional style programming would not find any
> surprises
> * all functions can be defined as copying functions
> * how many popular languages are designed (Ruby, Python, php, all 
> "functional" languages, etc...)

Yes, but all of these are languages where performance is not an imperative (excepting some of the 
functional languages perhaps). Plus think of all the time and effort that have been spent on GC's 
because of this design choice :)

> Cons:
> * could confuse people, lead to silent errors:
> toupper(str); // doesn't change str
> cos(x); // doesn't change x ;)
> 
> For the record, I am in favor of number 2 and that would have biased the 
> arguments above.

Likewise I'm in favor of #1 ;)

> 
> /Oskar



More information about the Digitalmars-d mailing list