[Issue 8743] Add support for memoizing class methods

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Oct 2 02:25:33 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=8743



--- Comment #5 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2012-10-02 02:25:42 PDT ---
(In reply to comment #4)
> void rehash() { memo = null; }
> 
> Maybe do you mean something like this?
> 
> void rehash() { memo.rehash; }
> void clear() { memo = null; }

Absolutely. I've used the wrong term here. Here's the snippet:

module test;

import std.stdio;
import std.traits;
import std.typecons;
import std.datetime;

template isClassStruct(alias fun)
{
    enum bool isClassStruct = (is(fun == class) || is(fun == struct));
}

mixin template memoize(alias fun, uint maxSize = uint.max)
    if (isClassStruct!(__traits(parent, fun)))
{
    ReturnType!fun[Tuple!(ParameterTypeTuple!fun)] memo;

    void rehash() { memo.rehash(); }
    void clear() { memo = null; }

    ReturnType!fun opCall(ParameterTypeTuple!fun args)
    {
        auto t = tuple(args);
        auto p = t in memo;
        if (p) return *p;
        static if (maxSize != uint.max)
        {
            if (memo.length >= maxSize) memo = null;
        }

        mixin("auto r = this." ~ __traits(identifier, fun) ~ "(args);");
        memo[t] = r;
        return r;
    }
}

class A 
{
    int field;

    int slowFunc(int a, int b) 
    { 
        int result;
        foreach (_; 0 .. 1024)
        {
            result += a;
            result += b;
        }
        return result + field;
    }

    mixin memoize!slowFunc fastFunc;
}

enum CallCount = 2048;

void main() 
{
    A a = new A;

    int z = a.fastFunc(100, 100);
    writeln(z);
    a.field = 50;
    a.fastFunc.clear();
    z = a.fastFunc(100, 100);
    writeln(z);
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list