medikoo / memoizee

Complete memoize/cache solution for JavaScript
ISC License
1.73k stars 61 forks source link

Why is the memoizee so slow? #127

Closed rudimadima closed 2 years ago

rudimadima commented 2 years ago

Simple example:

const memoize = require("memoizee");

function triangleArea(a, b, c) {
  if ((a + b <= c) || (b + c <= a) || (a + c <= b)) {
    throw new Error('Wrong triangle');
  }
  const p = (a + b + c) / 2;
  return Math.sqrt(p * (p - a) * (p - b) * (p - c));
};

const triangleAreaMemo = memoize(triangleArea);

let result1;
console.time('withoutCache');
for (let i = 0; i < 1000000; i++) {
  result1 = triangleArea(500, 500, 900);
}
console.timeEnd('withoutCache'); // 3.595ms

let result2;
console.time('withCache');
for (let i = 0; i < 1000000; i++) {
  result2 = triangleAreaMemo(500, 500, 900);
}
console.timeEnd('withCache'); // 74.507ms or 173.055ms with { primitive: true }

Why is the memoized function 20 times slower?

medikoo commented 2 years ago

@rudimadima thanks for opening. I've received a very similar question in the past, please see my answer, I think it explains well: https://github.com/medikoo/memoizee/issues/27#issuecomment-65617630

rudimadima commented 2 years ago

@medikoo, thank you for the answer!