Part 1: Climbing Mount Effect - Declarative Code and Effects Part 2: Reconcile all the things - Memoization, Data Flow and Reconciliation Part 3: Hea

Hackery, Math &  Design

submited by
Style Pass
2021-07-04 23:00:07

Part 1: Climbing Mount Effect - Declarative Code and Effects Part 2: Reconcile all the things - Memoization, Data Flow and Reconciliation Part 3: Headless React - Live, Yeet Reduce, No-API, WebGPU

If you have a slow function slow(x) in your code, one way to speed it up is to memoize it: you cache the last result inside, so that if it's called again with the same x, you get the same result. If the function is static, this is equivalent to just storing the last input and output in a global variable. If it's dynamic, you can use e.g. a closure as the storage:

This can only buy you time in small code bases with very limited use cases. As soon as you alternate between e.g. slow(a) and slow(b), your cache is useless. The easy solution is to upgrade to a multi-valued cache, where you can retain the outputs for both a and b. Problem is, now you need to come up with an eviction policy to keep your cache from growing indefinitely. This is also assuming that a and b are immutable values that can be compared, and not e.g. mutable trees, or URLs whose remote content you don't even know.

In garbage collected languages, there is a built-in solution to this, in the form of WeakMap. This is a key/value map that can hold data, but which does not own its keys. This means any record inside will be garbage collected unless another part of the program is also holding on to the same key. For this to work, keys must be objects, not primitive values.

Leave a Comment