The programming heuristic 'push ifs up and fors down' suggests that conditional logic (if statements) should be moved upward towards the caller, while iterative loops (fors) should be pushed downward toward batch processing. This improves clarity and performance by centralizing branching and leveraging bulk operations.
Matklad has discussed this principle, demonstrating how pushing conditionals up means the caller handles cases like None, while the function takes a plain Walrus. Pushing loops down involves deferring loops until after filtering, so the hot loop runs without a branch and is a candidate for vectorization. The two moves compose: given a collection of Option<Walrus> values, the caller discards the Nones and hands a Vec<Walrus> to frobnicate_batch, which never sees a None.
This principle has broader applications in relational database query optimizations and functional programming. In database query optimization, the same principle appears as 'projections early, joins late'. Early projections and selections reduce dataset width and filter early, while joins are deferred to run on smaller inputs. The vocabulary runs upside-down: a query plan is a tree where data flows up from leaves, so 'down the tree' means 'earlier in execution'.
Source: Hacker News · Summarized by HeadlinesBriefing