PoC: Cached function calls
janderson
askme at me.com
Sun Dec 17 03:29:20 PST 2006
Nice, I really like these type of algorithms. I once wrote a C++ one to
move the vtable of objects to a local area in memory to avoid double
seeking. One optimisation you may consider (if it hasn't already been
added is:
Change
> # p_cache[node] = Func(args);
> # result = node in p_cache;
To
> # result = Func(args);
> # p_cache[node] = result;
That way you avoid an unnecessary lookups. Unless D is smart enough to
do the optimisation itself which would be nice but unlikely.
Chris Nicholson-Sauls wrote:
> # import std .traits ;
> #
> # struct TCachedFunc (alias Func) { static:
> #
> # alias ReturnType !(Func) Ret ;
> # alias ParameterTypeTuple !(Func) Params ;
> #
> # static if (is(typeof(Params[1]))) {
> # // multiple parameters
> #
> # private struct Node {
> # Params params ;
> # }
> #
> # private Ret[Node] p_cache ;
> #
> # Ret opCall (Params args) {
> # Node node ;
> # Ret* result ;
> #
> # foreach (i, x; args) {
> # node.params[i] = x;
> # }
> # result = node in p_cache;
> #
> # if (!result) {
> # p_cache[node] = Func(args);
> # result = node in p_cache;
> # }
> # return *result;
> # }
> # }
> # else {
> # // single parameter
> #
> # alias Params[0] Param ;
> #
> # private Ret[Param] p_cache ;
> #
> # Ret opCall (Param arg) {
> # Ret* result = arg in p_cache;
> #
> # if (!result) {
> # p_cache[arg] = Func(arg);
> # result = arg in p_cache;
> # }
> # return *result;
> # }
> # }
> # }
> -- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list