I think it was Stefan Glienke who pointed me at the Memoisation pattern: [WayBack] Implementing 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
Like this:
Like Loading...