1

I’m trying to improve the performance of a computationally expensive JavaScript function by memoizing it. The function accepts multiple arguments, including objects. Here's an example:

function expensiveCalculation(a, b, options) {
    // Simulating an expensive operation
    return a + b + options.value;
}

const options = { value: 10 };
console.log(expensiveCalculation(5, 3, options)); // 18
console.log(expensiveCalculation(5, 3, options)); // Should use the cached result

memoizedCalculation(5, 3, options);

3
  • Is it reasonable to hash the args to use as a caching key? Or are there like huge buffers and stuff in your args? Commented Nov 28, 2024 at 18:34
  • had you have a look here? Commented Nov 28, 2024 at 18:58
  • 3
    What exactly is the problem? Do you know how to memoise a function in general? Commented Nov 29, 2024 at 3:01

1 Answer 1

0

Memoizing can be done in many different ways. A typical approach of doing it would be to define a function in a scope together with a map (here: cache) that acts as a static memory for any previously calculated results:

const fn = (()=>{
 let res;
 const cache=new Map();
 return function(a,b,options) {
   const key=`${a},${b},${options.value}`;
  // Simulating an expensive operation
  res=cache.get(key);
  if(res===undefined) {
   console.log("calculating");
   // the lengthy computation:
   res=a+b+options.value
   cache.set(key,res);
  }
  return res;
 }
})();

// Now, run some tests:
console.log([fn(2,3,{value:4}),
fn(2,3,{arr:[1,2,3],value:4}),
fn(2,3,{value:4,name:"new"})]);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.