DMD 2.000 alpha release

Chris Nicholson-Sauls ibisbasenji at gmail.com
Wed Jun 20 14:12:24 PDT 2007


eao197 wrote:
> On Wed, 20 Jun 2007 17:39:43 +0400, Chris Nicholson-Sauls 
> <ibisbasenji at gmail.com> wrote:
> 
>>>> This is going to save me plenty of memory costs (imagine, no longer 
>>>> .dup'ing lots of strings and other arrays just to play it safe 
>>>> against silly end users modifying what they shouldn't) not to 
>>>> mention debugging headaches.
>>>  How do you plain to reduce count of .dup's in D 2.0?
>>>
>>
>> By returning const views rather than copies.  Or in some cases, 
>> referances to invariant data.
> 
> Do you mean something like:
> 
> class Demo
>   {
>     this( const char * name )
>       {
>         name_ = name.dup;
>       }
> 
>     const char *
>     getName() { return name_; }
> 
>   private:
>     char[] name_;
>   }
> 
> instead of
> 
>   char[]
>   getName() { return name_.dup; }
> 
> ?
> 

Rough draft off the top of my head, working from an actual project:

# module bovis .types .Symbol ;
#
# // includes: alias char[] BString
# private import bovis .types .Basic ;
#
# public final class BSymbol {
#
#   private static BSymbol[invariant BString] p_pool ;
#
#   public static BSymbol opIndex (BString str) {
#     BSymbol result ;
#
#     if (auto ptr = str in p_pool) {
#       result = *ptr;
#     }
#     else {
#       result = new BSymbol(str);
#       p_pool[str.idup] = result;
#     }
#     return result;
#   }
#
#   private invariant(BString) m_str ;
#
#   private this (BString str) {
#     m_str = str.idup ;
#   }
#
#   public invariant(BString) string () {
#     return m_str ;
#   }
#
# }

Usage:
auto alpha = BSymbol["test"] ;
auto beta  = BSymbol["test"] ;
assert(alpha is beta);

(The use of this isn't obvious I know.  Just trust me that it has great 
utility in the program its part of.)

Now first, yes, there are two .idup's in there.  I'm not sure if they're 
neccessary or not, and haven't tested things yet.  But... in the 
original, there are /three/ .dup's.  I can now do away with the one in 
.string(), which is the one I'm most worried about, since the duplicate 
it would've created is short-lived.  (The other two are very long-lived; 
life of the program, in theory.)  Thus, having those 'invariant's in 
there lets me avoid a myriad of needless copies -- I can just copy it on 
the user side if I need to, most likley happening automatically as part 
of a concatenation.

Now I just need to a chance to test this to see if it all works in the 
way my head seems to have it organized.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-announce mailing list