Lesson 2 · Unit 02
Caching
Remember answers, and know when not to
What you practise
- Memoising a pure function, cache keys, hit rate and the average cost it gives, eviction (least recently used), stale entries
Try a question from this lesson
Pick one
A page makes 500 price lookups, but only 20 different products appear. A lookup takes 10 ms. How long do they take in all if each product is fetched once and remembered?
Correct answer
200 ms
Why
20 real fetches at 10 ms each is 200 ms; the other 480 calls are answered from memory. Without remembering it is 5,000 ms. A cache trades a little memory for not doing the same work twice.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Hits and misses
A cache stores answers under a key.
Hit: the key is there, and the stored answer comes back at once.
Miss: the key is not there. Do the real work, then store the result.
Memoising is a cache wrapped around a function, keyed by its arguments. It is safe only for a pure function: the same arguments always give the same result, and calling it changes nothing else.
11 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 5× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.