D1 -> D2

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 18 13:02:40 PST 2010


On Thu, 18 Nov 2010 15:49:10 -0500, Walter Bright  
<newshound2 at digitalmars.com> wrote:

> Steven Schveighoffer wrote:
>> It's not impossible, but Tango's #1 rule is minimize heap allocations.   
>> By peppering idup everywhere, you have created a conflict with the main  
>> goal.  Refactoring in these cases isn't quite as simple as you say, and  
>> it certainly won't be backwards compatible.
>
> If you know the string is unique, you can use cast(string) rather than  
> .idup, and no allocations will be done.

class obj
{
    char[] name;
    this(char[] name) { this.name = name;}
}

What to do there?  If name is typically a string literal, then string is  
appropriate.  But if there are cases where a name is passed in via a  
char[] allocated on the heap, then const(char) makes sense.  However, you  
really don't want the name to change at some other point, so if it's not  
immutable it should idup the name.

It's not easy to make this code both safe and efficient.  In the end, I  
think in cases like this I did something like:

string name;
this(const(char)[] name) { this.name = name.idup;}
this(string name) {this.name = name;}

These are the kinds of cases I was talking about.  They require more than  
simple "search and replace" refactoring.  In reality, the original code is  
unsafe and flawed, but you want to try and support any existing code that  
uses it as well as possible.  There was also some anti-D2 sentiments to  
overcome when trying to get Tango to accept a D2 port, so I wanted to try  
and make the port as painless as possible.

-Steve


More information about the Digitalmars-d mailing list