Object.opEquals, opCmp, toHash

bearophile bearophileHUGS at lycos.com
Thu Feb 16 10:12:24 PST 2012


Stewart Gordon:

> For example, if the source code is
> 
>      string toString() const pure {
>          return ...;
>      }
> 
> then the compiler would generate code equivalent to
> 
>      bool _has_cached_toString;
>      string _cached_toString;
> 
>      string toString() {
>          if (!_has_cached_toString) {
>              _cached_toString = ...;
>              _has_cached_toString = true;
>          }
>          return _cached_toString;
>      }

The purpose of using an explicit @memoize is to offer the programmer the choice to enable or disable such caching. On default there is no caching.

If toString() is requires only rarely and the string is large but quick to compute, you probably don't wait it to be cached, so you don't add @memoize. If toHash is needed often, and its computation requires some time, given that it only requires one word of memory, you probably want to add @memoize.

The compiler is then free to implement @memoize with a dictionary when there are arguments and with a bool+field when the memoized method has no arguments.

Bye,
bearophile


More information about the Digitalmars-d mailing list