0

This is a memoization example from freecodecamp. The first 2 lines seem to achieve the same goal, determining the presence of an object key.

But using the first if-statement takes significantly longer to run, as if never even checks the memo object. How do these work differently?

const howSum = (targetSum, array, memo={}) => {
  // if (memo[targetSum]) return memo([targetSum]); // why does this take longer?
  if (targetSum in memo) return memo[targetSum];    // than this if-statement?
  if (targetSum === 0) return [];
  if (targetSum < 0) return null;

  for (var num of array) {
    var remainder = targetSum - num;
    var remainderResult = howSum(remainder, array, memo);
    if (remainderResult !== null) {
      memo[targetSum] = [...remainderResult, num];
      return [ ...remainderResult, num ];
    }
  }
  memo[targetSum] = null;
  return null;
}

console.log(howSum(7, [2, 3]));  // [3, 2, 2]
console.log(howSum(300, [7, 14]));  // null
jakeb1050
  • 23
  • 2
  • 3
    `'x' in { x: undefined }` is `true` (there is a property `x`), which is different from testing "truthiness" of any property `x` that may or may not existing in the object. – crashmstr Aug 30 '21 at 18:25
  • Hoping `return memo([targetSum])` should be `return memo[targetSum]`. Also how are you calculating the speed? How big are your objects/computations? – Tushar Shahi Aug 30 '21 at 18:28
  • 1
    commented out line has to determine if index exists, access the element, and determine its "truthiness". The 2nd case just determines if the index exists. – Garr Godfrey Aug 30 '21 at 18:30
  • @GarrGodfrey, correct. I was wondering why this is slower, couldn't find anything. But `in` also checks all up the property chain right, shouldn't that compensate it? – Tushar Shahi Aug 30 '21 at 18:32
  • 1
    Actually, I think the speed difference is the when memo[targetSum] is null. The first once evaluates to "false" so it will run through the array and search again. The second one evaluates to true so returns null instantly. – Garr Godfrey Aug 30 '21 at 18:36
  • You're basically asking why one check (key exists) is faster than two checks (key exists, has truthy value)? – Jonas Wilms Aug 30 '21 at 18:36

0 Answers0