简体   繁体   中英

Javascript Memoization Implementation

I've been debating this topic with my mates at work. I would like to know from you guys, if this is, actually, the right way of implementing the memoization.

 function memoize(result) { let cache = {}; return function() { if (cache[result]) { // returns cached result / no calculation return cache[result]; } // calculating... cache[result] = result; return cache[result]; }; } function expensiveCalculation() { let counter = 0; for (let i = 0; i < 1000000; i++) { counter += i; } return counter; } console.time("FirstCalculation"); const memoizedExpensiveCalculation = memoize(expensiveCalculation()); console.timeEnd("FirstCalculation"); console.time("1_Memoized"); memoizedExpensiveCalculation(); console.timeEnd("1_Memoized"); console.time("2_Memoized"); memoizedExpensiveCalculation(); console.timeEnd("2_Memoized"); console.time("3_Memoized"); memoizedExpensiveCalculation(); console.timeEnd("3_Memoized");

The time logs reveals, in fact, the first time takes much more time (which we would expect) and less time afterwards.

it's not correct


The code you shows

function memoize(result) {
  let cache = {};

  return function() {
    if (cache[result]) {
      // returns cached result / no calculation
      return cache[result];
    }
    // calculating...
    cache[result] = result;
    return cache[result];
  };
}

is basically

function memoize(result) {
  return result
}

in memoization what you cache is input/output pair and skip real function call when input match.

something like:

function get(func) {
  let cache = {};

  return function(key) {
    if (key in cache) {
      return cache[key];
    }
    cache[key] = func(key);
    return cache[key];
 };
}

function expensiveCalculation(param) {
  console.log('expensive calculation runs')
  let counter = 0;
  for (let i = 0; i < 10000; i++) {
    counter += i;
  }
  return param*2;
}
const memo = get(expensiveCalculation)
console.log('start')
console.log('first try');
console.log(memo(10));
console.log('second try');
console.log(memo(10));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM