Reputation: 105517
I'm reading memoization chapter of John Resig's book about Javascript and I've got the following question:
Is it better to develop memoization for a method or create cache as object's property assuming that I can modify object's design?
This example implements caching as part of object's functionality:
function Calc() {
this._cache = {};
this.isEven = function(arg) {
return this._cache[arg] !== undefined ?
this._cache[arg] :
this._cache[arg] = (arg%2===0);
}
}
This example implements caching as part of function's functionality:
function Calc() {
this.isEven = function(arg) {
this.isEven.cache = this.isEven.cache || {};
return this.isEven.cache[arg] !== undefined ?
this.isEven.cache[arg] :
this.isEven.cache[arg] = (arg%2===0);
}
}
This is the way they should be used:
var obj = new Calc();
obj.isEven(3);
Upvotes: 3
Views: 102
Reputation: 324750
Well, here's the thing: what if you had an "isOdd" function? You would want it to have its own cache, so the second option is easier.
That being said, this isn't really a good example, because x%2==0
is a really cheap operation, so it shouldn't be made into a function.
Upvotes: 1