Memoize Implementation Using Eval. Is This Use Of Eval Acceptable?
...or are there better ways to implement a Memoization? Function.memoize = function(callableAsString) { var r = false, callable, code; try { callable =
Solution 1:
I don't see the need for eval... consider this implementation
functionmemoize(f, cache)
{
if (!cache) cache = {};
returnfunction()
{
var key = JSON.stringify(arguments);
return (cache[key] || (cache[key] = [f.apply(this, arguments)]))[0];
}
}
Note that I deliberately ignored this
in the key. The reason is that this
may not be serializable by stringify
(e.g. because of loops) and this is more the rule than the exception for example when this == window
i.e. in the global context.
What is IMO useful is the ability to explictly pass the cache, so that you can for example create a separate cache for each instance or one shared cache for all instances by doing something like:
functionMyObj(...)
{
// every instance has its own cachethis.foo = memoize(function(...) { ... });
// there is one shared cache for all instancesthis.bar = memoize(function(...) { ... }, MyObj.memoize_cache);
}
MyObj.memoize_cache = {};
Post a Comment for "Memoize Implementation Using Eval. Is This Use Of Eval Acceptable?"