How can I do lazy variable initialization?
    Jack 
    jckj33 at gmail.com
       
    Sat Jan  9 21:47:00 UTC 2021
    
    
  
On Saturday, 9 January 2021 at 20:39:26 UTC, Ali Çehreli wrote:
> On 1/9/21 12:35 PM, Ali Çehreli wrote:
>
> > alias lightLoadOperation = memoize!heavyLoadOperation;
> >
> >    const l = lightLoadOperation();
>
> Well, that doesn't work the way you want but this does:
>
>   if (args.length == 1) {
>     writefln!"Using lazy variable: %s %s"(lightLoadOperation(), 
> lightLoadOperation());
>   }
>
> No matter how many times you call lightLoadOperation, it will 
> be called just once (which can be configured with maxSize):
>
>   https://dlang.org/library/std/functional/memoize.html
>
> Ali
In case of a function that takes no arguments ever, using memoize 
may add memory overhead and something like this:
bool loaded = false;
T heavyLoadOperation() {
   if(!loaded) {
      // ... heavy operation.
     loaded = true;
   }
   return value;
}
can actually be better in terms of memory usage? I thought the 
lazy keyword could somehow help here but I think the way to go is 
is just use a flag, such as loaded bool variable.
    
    
More information about the Digitalmars-d-learn
mailing list