The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My work

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,311 other followers

Implementing Memoize in Delphi 2009 – Community Blogs – Embarcadero Community

Posted by jpluimers on 2017/11/28

I think it was Stefan Glienke who pointed me at the Memoisation pattern: [WayBackImplementing Memoize in Delphi 2009 – Community Blogs – Embarcadero Community

Or in laymans terms: caching with generic functions and dictionaries.

Note the Archive.is link is way better readable than the WayBack link, so below I’ve saved parts only in Archive.is.

It points to two other interesting reads:

Later I found it was indeed Stefan who pointed me to the above links and also came up with this very small Memoisation example which is based on Spring4D:

and guess what? because we have interfaced based dictionary this is super easy, let me just hack an example, 5mins6:52 PM

function BuildCache: Tfunc<string,string>;
var
 cache: IDictionary<string,string>;
begin
 cache := TCollections.CreateDictionary<string,string>;
 Result :=
   function(s: string): string
   begin
     if not cache.TryGetValue(s, Result) then
     begin
       Sleep(1000); // hard work! ;)
       Result := ReverseString(s);
       cache.Add(s, Result);
     end;
   end;
end;

Since the returned anonymous method captures the dictionary its kept inside and once the anonymous method goes out of scope the dictionary is also cleaned, want to reset the cache? Just create a new one and throw the old one away.

Need thread safety? just add

System.TMonitoy.Enter/Leave(cache.AsObject);

–jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: