ko.computed or ko.pureComputed for view models with many rarely-observed computeds?
0 reputation · 04 Aug 2021, 06:29 UTC
I'm designing a Knockout view-model layer (Knockout 3.5.x) where a large list rendered with foreach produces many item view models, each carrying several computed values. Most of those computeds are only observed while their row is visible or bound, and the view models themselves can live for a long time.
The documented trade-off is clear in outline: ko.computed evaluates eagerly and keeps its subscriptions and cached value alive even with zero observers, while ko.pureComputed (available since 3.2) subscribes to its dependencies only while it has subscribers and goes to sleep otherwise, reevaluating on next read. Pure computeds look like the obvious fit for memory pressure, but the documentation also warns that their evaluators must not have side effects, and eager evaluation is sometimes exactly what you want when a subscription must fire regardless of UI observers.
What I'm missing is a principled rule for choosing between them at the codebase level rather than case by case.
Specifically:
- Is defaulting everything to
ko.pureComputedand opting back intoko.computedonly where eager evaluation is required a sound convention, or does the sleep/wake reevaluation behavior create subtle bugs that make the reverse default safer? - For computeds whose evaluator writes to other observables (a documented side-effect risk when asleep), is the accepted pattern to keep them as
ko.computed, or to restructure them as explicit subscriptions? - Does mixing both kinds in one dependency chain (a pure computed depending on an eager computed) have any documented pitfalls around evaluation order or missed notifications?