Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use memoization or object's cache

Tags:

javascript

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);
like image 271
Max Koretskyi Avatar asked May 22 '26 02:05

Max Koretskyi


1 Answers

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.

like image 63
Niet the Dark Absol Avatar answered May 24 '26 18:05

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!