[{"data":1,"prerenderedAt":97},["ShallowReactive",2],{"course-en-memoization":3},{"lesson":4,"number":88,"prev":89,"next":93},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":58,"exercises":69},"memoization",{"ru":7,"en":8},"","Memoization",{"ru":7,"en":10},"Memoization in JavaScript: caching pure function results in a closure, cache keys, Ramda's R.memoizeWith, recursive Fibonacci, memory cost and invalidation.",{"ru":7,"en":12},"Understand how memoization caches the results of a pure function, learn to write your own memoize and use R.memoizeWith, choose a cache key, speed up recursion, and account for memory cost and invalidation.",[14,17,19,23,25,28,30,33,35,38,40,42,44,47,49,51,53,56],{"type":15,"ru":7,"en":16},"text","Memoization is caching a function's results by its arguments. On the first call the function computes the result and remembers it, and on a repeated call with the same arguments it returns the stored value without computing it again. The term was coined by the British researcher Donald Michie in 1968.",{"type":15,"ru":7,"en":18},"The cache lives in a closure: memoize returns a wrapper, and only that wrapper can reach the stored results. A Map is a convenient cache: any value can be a key, and keys are compared almost as with ===, except that NaN is considered equal to NaN.",{"type":20,"code":21},"code",{"ru":7,"en":22},"\u002F\u002F memoize :: (a -> b) -> (a -> b)\n\u002F\u002F for functions of one argument: the cache key is the argument itself\nconst memoize = (fn) => {\n  \u002F\u002F the cache lives in the closure: nothing outside can reach it\n  const cache = new Map()\n  return (arg) => {\n    if (cache.has(arg)) {\n      return cache.get(arg)\n    }\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n\n\u002F\u002F the counter shows how many times the function actually computed;\n\u002F\u002F it is a side effect, here only for illustration\nlet calls = 0\n\n\u002F\u002F countDivisors :: Number -> Number\n\u002F\u002F checks every number from 1 to n: the larger n, the longer it takes\nconst countDivisors = (n) => {\n  calls += 1\n  return R.range(1, n + 1).filter((i) => n % i === 0).length\n}\n\nconst countDivisorsMemo = memoize(countDivisors)\n\nconsole.log(countDivisorsMemo(360)) \u002F\u002F 24\nconsole.log(countDivisorsMemo(360)) \u002F\u002F 24, from the cache\nconsole.log(countDivisorsMemo(1000)) \u002F\u002F 16\nconsole.log('computations: ' + calls) \u002F\u002F computations: 2",{"type":15,"ru":7,"en":24},"Only pure functions can be memoized. The cache replaces a call with the stored result, and that is safe only when the function always returns the same thing for the same arguments and changes nothing outside. If the result depends on an outside variable, the cache returns a stale value. If the function writes or sends something, repeated calls simply won't do it.",{"type":26,"ru":7,"en":27},"heading","The cache key",{"type":15,"ru":7,"en":29},"The key decides which calls count as the same. For a single primitive argument the argument itself is the key. A Map compares objects by reference: an object with the same contents but created anew won't be found, while an object changed in place will be found together with a stale result. That is why memoization goes well with the immutable data from the \"Immutability\" lesson: a new value means a new object and a new key.",{"type":20,"code":31},{"ru":7,"en":32},"\u002F\u002F memoize from the previous example\n\u002F\u002F memoize :: (a -> b) -> (a -> b)\nconst memoize = (fn) => {\n  const cache = new Map()\n  return (arg) => {\n    if (cache.has(arg)) {\n      return cache.get(arg)\n    }\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n\n\u002F\u002F === an impure function: the result depends on an outside variable ===\nlet rate = 90\n\u002F\u002F toRub :: Number -> Number\nconst toRub = (usd) => usd * rate\nconst toRubMemo = memoize(toRub)\n\nconsole.log(toRubMemo(10)) \u002F\u002F 900\nrate = 100\nconsole.log(toRub(10)) \u002F\u002F 1000\nconsole.log(toRubMemo(10)) \u002F\u002F 900: the rate has changed, but the result comes from the cache\n\n\u002F\u002F === an object key is compared by reference ===\nlet lengthCalls = 0\n\u002F\u002F nameLength :: Object -> Number\nconst nameLength = memoize((user) => {\n  lengthCalls += 1\n  return user.name.length\n})\n\nconst john = { name: 'John' }\nconsole.log(nameLength(john)) \u002F\u002F 4\n\u002F\u002F the same contents but a different object: the cache didn't help\nconsole.log(nameLength({ name: 'John' })) \u002F\u002F 4\nconsole.log('computations: ' + lengthCalls) \u002F\u002F computations: 2\n\n\u002F\u002F the object was changed in place, the reference is the same: the cache returns the old answer\njohn.name = 'Johnny'\nconsole.log(nameLength(john)) \u002F\u002F 4, although the name now has 6 letters",{"type":15,"ru":7,"en":34},"Ramda has R.memoizeWith(keyFn, fn): the first function builds a key from the arguments, the second computes the result. The cache inside is a plain object, so the key must be a string. Anything else is converted to a string, and every object turns into the same key \"[object Object]\". With several arguments, the key is built with a separator: without it the calls (1, 23) and (12, 3) would give the same string \"123\".",{"type":20,"code":36},{"ru":7,"en":37},"let calls = 0\n\u002F\u002F area :: (Number, Number) -> Number\nconst area = (width, height) => {\n  calls += 1\n  return width * height\n}\n\n\u002F\u002F a key built from both arguments with a separator\nconst areaMemo = R.memoizeWith((width, height) => width + 'x' + height, area)\n\nconsole.log(areaMemo(2, 3)) \u002F\u002F 6\nconsole.log(areaMemo(2, 3)) \u002F\u002F 6, from the cache\nconsole.log(areaMemo(3, 2)) \u002F\u002F 6, but the key is different: 3x2\nconsole.log('computations: ' + calls) \u002F\u002F computations: 2\n\n\u002F\u002F === a mistake: an object as the key ===\n\u002F\u002F R.identity returns the object itself, and as a string it becomes '[object Object]'\nconst getName = R.memoizeWith(R.identity, (user) => user.name)\nconsole.log(getName({ id: 1, name: 'John' })) \u002F\u002F John\nconsole.log(getName({ id: 2, name: 'Anna' })) \u002F\u002F John: someone else's result from the cache\n\n\u002F\u002F the key must be a string that tells the objects apart\nconst getNameById = R.memoizeWith((user) => String(user.id), (user) => user.name)\nconsole.log(getNameById({ id: 1, name: 'John' })) \u002F\u002F John\nconsole.log(getNameById({ id: 2, name: 'Anna' })) \u002F\u002F Anna",{"type":26,"ru":7,"en":39},"Recursion: Fibonacci numbers",{"type":15,"ru":7,"en":41},"Memoization pays off most where a function is called many times with the same arguments. The classic example is Fibonacci numbers: fib(n) = fib(n - 1) + fib(n - 2). Naive recursion computes the same values again and again, and the number of calls grows exponentially: 21,891 for fib(20) and already 2,692,537 for fib(30).",{"type":15,"ru":7,"en":43},"For memoization to work, the recursive calls must go through the memoized version. If you wrap a finished function from the outside, only the top call gets into the cache, and the recursion inside bypasses it.",{"type":20,"code":45},{"ru":7,"en":46},"\u002F\u002F memoize :: (a -> b) -> (a -> b)\nconst memoize = (fn) => {\n  const cache = new Map()\n  return (arg) => {\n    if (cache.has(arg)) {\n      return cache.get(arg)\n    }\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n\n\u002F\u002F === naive recursion ===\nlet naiveCalls = 0\n\u002F\u002F fib :: Number -> Number\nconst fib = (n) => {\n  naiveCalls += 1\n  return n \u003C 2 ? n : fib(n - 1) + fib(n - 2)\n}\n\nconsole.log(fib(20)) \u002F\u002F 6765\nconsole.log('calls: ' + naiveCalls) \u002F\u002F calls: 21891\n\n\u002F\u002F === a wrapper outside: the recursion bypasses the cache ===\nnaiveCalls = 0\nconst fibWrapped = memoize(fib)\nconsole.log(fibWrapped(20)) \u002F\u002F 6765\n\u002F\u002F fib calls itself inside, not fibWrapped\nconsole.log('calls: ' + naiveCalls) \u002F\u002F calls: 21891\n\u002F\u002F only the top call is in the cache: fibWrapped(20)\nconsole.log(fibWrapped(20)) \u002F\u002F 6765\nconsole.log('calls: ' + naiveCalls) \u002F\u002F calls: 21891\n\n\u002F\u002F === recursion through the memoized function ===\nlet memoCalls = 0\n\u002F\u002F fibMemo :: Number -> Number\nconst fibMemo = memoize((n) => {\n  memoCalls += 1\n  return n \u003C 2 ? n : fibMemo(n - 1) + fibMemo(n - 2)\n})\n\nconsole.log(fibMemo(20)) \u002F\u002F 6765\n\u002F\u002F each n from 0 to 20 is computed once\nconsole.log('computations: ' + memoCalls) \u002F\u002F computations: 21\nconsole.log(fibMemo(30)) \u002F\u002F 832040\n\u002F\u002F only n from 21 to 30 were added\nconsole.log('computations: ' + memoCalls) \u002F\u002F computations: 31",{"type":26,"ru":7,"en":48},"Memory cost and invalidation",{"type":15,"ru":7,"en":50},"A cache takes memory and does not clean itself up. If the arguments hardly ever repeat, for example request IDs or text the user types, the cache grows with every call and saves nothing. R.memoizeWith hides its cache in a closure: you can neither limit nor clear it, you can only create a new memoized function.",{"type":15,"ru":7,"en":52},"Hence two techniques. The first is to limit the size. A Map remembers insertion order, so when it overflows you can delete the first entry, and move an entry to the end whenever it is accessed. This gives an LRU (least recently used) cache: it evicts whatever was accessed longest ago. The second is invalidation. If the result depends on data that changes, put the data version into the key or drop the whole cache. For object keys there is WeakMap: an entry in it doesn't stop the garbage collector from removing the object once nothing else refers to it.",{"type":20,"code":54},{"ru":7,"en":55},"\u002F\u002F memoizeLimited :: Number -> (a -> b) -> (a -> b)\n\u002F\u002F an LRU cache of limit entries with a manual reset\nconst memoizeLimited = (limit) => (fn) => {\n  const cache = new Map()\n  const memoized = (arg) => {\n    if (cache.has(arg)) {\n      const value = cache.get(arg)\n      \u002F\u002F move the entry to the end: it was used most recently\n      cache.delete(arg)\n      cache.set(arg, value)\n      return value\n    }\n    const result = fn(arg)\n    cache.set(arg, result)\n    if (cache.size > limit) {\n      \u002F\u002F the first entry in the Map is the one accessed longest ago\n      cache.delete(cache.keys().next().value)\n    }\n    return result\n  }\n  \u002F\u002F invalidation: drop the whole cache\n  memoized.clear = () => cache.clear()\n  memoized.size = () => cache.size\n  return memoized\n}\n\nlet calls = 0\n\u002F\u002F square :: Number -> Number\nconst square = (n) => {\n  calls += 1\n  return n * n\n}\n\nconst squareMemo = memoizeLimited(2)(square)\n\nsquareMemo(1) \u002F\u002F computed\nsquareMemo(2) \u002F\u002F computed\nsquareMemo(1) \u002F\u002F from the cache, 1 is now the most recent entry\nsquareMemo(3) \u002F\u002F computed, the cache overflows: 2 is evicted\nsquareMemo(1) \u002F\u002F from the cache\nsquareMemo(2) \u002F\u002F 2 was evicted, computed again\nconsole.log('computations: ' + calls + ', cached: ' + squareMemo.size()) \u002F\u002F computations: 4, cached: 2\n\nsquareMemo.clear()\nsquareMemo(1) \u002F\u002F computed again after the reset\nconsole.log('computations: ' + calls + ', cached: ' + squareMemo.size()) \u002F\u002F computations: 5, cached: 1",{"type":15,"ru":7,"en":57},"Memoization pays off when the function is pure, takes noticeably longer than building a key and looking up an entry, and is called with repeating arguments. Typical cases are recursion with overlapping subproblems, parsing and formatting the same strings, and computing derived data from state. For cheap functions like addition a cache only adds work and memory. As in the \"Performance\" lesson, check the gain by measuring rather than by a single run: count computations and cache hits, or repeat time measurements.",[59,61,63,65,67],{"ru":7,"en":60},"Memoization remembers a function's result by its arguments and, on a repeated call with the same arguments, returns it from a cache that lives in a closure.",{"ru":7,"en":62},"Only pure functions can be memoized: otherwise the cache returns a stale result or skips a side effect.",{"ru":7,"en":64},"The cache key decides which calls are the same: a Map compares objects by reference, R.memoizeWith(keyFn, fn) expects a string key, and for several arguments the key is built with a separator.",{"ru":7,"en":66},"In recursion the calls must go through the memoized function: fib(20) without a cache makes 21,891 calls, and with a cache it computes 21 values.",{"ru":7,"en":68},"A cache costs memory and doesn't clean itself up: its size is limited by evicting old entries, and when outside data changes the cache is dropped or the data version is put into the key.",[70,79],{"task":71,"starter":73,"solution":75,"expected":77},{"ru":7,"en":72},"paths(rows, cols) counts how many paths lead from the top-left corner of a grid to the bottom-right one if you can only move right or down. Naive recursion makes hundreds of thousands of calls for a 10 by 10 grid. Write pathsMemo with R.memoizeWith: the recursive calls must go through the cache, and the key must tell pairs of arguments apart. Compare the number of calls and computations.",{"ru":7,"en":74},"let naiveCalls = 0\n\u002F\u002F paths :: (Number, Number) -> Number\nconst paths = (rows, cols) => {\n  naiveCalls += 1\n  if (rows === 0 || cols === 0) return 1\n  return paths(rows - 1, cols) + paths(rows, cols - 1)\n}\n\nconsole.log(paths(10, 10))\nconsole.log('without a cache, calls: ' + naiveCalls)\n\nlet memoCalls = 0\n\u002F\u002F your code: pathsMemo with R.memoizeWith, increment memoCalls inside\n\nconsole.log(pathsMemo(10, 10))\nconsole.log('with a cache, computations: ' + memoCalls)",{"ru":7,"en":76},"let naiveCalls = 0\n\u002F\u002F paths :: (Number, Number) -> Number\nconst paths = (rows, cols) => {\n  naiveCalls += 1\n  if (rows === 0 || cols === 0) return 1\n  return paths(rows - 1, cols) + paths(rows, cols - 1)\n}\n\nconsole.log(paths(10, 10))\nconsole.log('without a cache, calls: ' + naiveCalls)\n\nlet memoCalls = 0\n\u002F\u002F pathsMemo :: (Number, Number) -> Number\n\u002F\u002F a key from both arguments with a separator, the recursion goes through pathsMemo\nconst pathsMemo = R.memoizeWith(\n  (rows, cols) => rows + ',' + cols,\n  (rows, cols) => {\n    memoCalls += 1\n    if (rows === 0 || cols === 0) return 1\n    return pathsMemo(rows - 1, cols) + pathsMemo(rows, cols - 1)\n  },\n)\n\nconsole.log(pathsMemo(10, 10))\n\u002F\u002F each pair (rows, cols) is computed once\nconsole.log('with a cache, computations: ' + memoCalls)",{"ru":7,"en":78},"184756\nwithout a cache, calls: 369511\n184756\nwith a cache, computations: 120",{"task":80,"starter":82,"solution":84,"expected":86},{"ru":7,"en":81},"priceWithTax takes the tax rate in percent from the outside variable taxPercent, so the memoized version returns old prices after the rate changes. Make the function pure: the rate must come in as an argument. Memoize it with R.memoizeWith so that the rate is part of the key. Call priceMemo for the price 100 twice at a 20% rate and once at 10%, print all three prices and then the number of computations, which the calls counter from the starter keeps.",{"ru":7,"en":83},"\u002F\u002F memoize for functions of one argument\n\u002F\u002F memoize :: (a -> b) -> (a -> b)\nconst memoize = (fn) => {\n  const cache = new Map()\n  return (arg) => {\n    if (cache.has(arg)) {\n      return cache.get(arg)\n    }\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n\n\u002F\u002F the counter shows how many times the function actually computed;\n\u002F\u002F it is a side effect, here only for illustration\nlet calls = 0\n\nlet taxPercent = 20\n\u002F\u002F priceWithTax :: Number -> Number\nconst priceWithTax = (price) => {\n  calls += 1\n  return price + (price * taxPercent) \u002F 100\n}\nconst priceMemo = memoize(priceWithTax)\n\nconsole.log(priceMemo(100))\ntaxPercent = 10\n\u002F\u002F the rate is 10% now, but the price is old\nconsole.log(priceMemo(100))\n\n\u002F\u002F your code",{"ru":7,"en":85},"\u002F\u002F the counter shows how many times the function actually computed;\n\u002F\u002F it is a side effect, here only for illustration\nlet calls = 0\n\u002F\u002F the rate is an argument now: the result depends only on the arguments, as with a pure function\n\u002F\u002F priceWithTax :: (Number, Number) -> Number\nconst priceWithTax = (percent, price) => {\n  calls += 1\n  return price + (price * percent) \u002F 100\n}\n\n\u002F\u002F the rate is part of the key: a new rate means a new key\nconst priceMemo = R.memoizeWith((percent, price) => percent + '|' + price, priceWithTax)\n\nlet taxPercent = 20\nconsole.log(priceMemo(taxPercent, 100))\n\u002F\u002F the same key 20|100: from the cache\nconsole.log(priceMemo(taxPercent, 100))\ntaxPercent = 10\n\u002F\u002F the key 10|100: computed again\nconsole.log(priceMemo(taxPercent, 100))\nconsole.log('computations: ' + calls)",{"ru":7,"en":87},"120\n120\n110\ncomputations: 2",16,{"slug":90,"title":91},"performance",{"ru":7,"en":92},"Performance",{"slug":94,"title":95},"transducers",{"ru":7,"en":96},"Transducers",1792684725057]