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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With