← Previous · All Episodes · Next →
Mastering Code Flow with Two Simple Rules Push Ifs Up and Push Fors Down Episode

Mastering Code Flow with Two Simple Rules Push Ifs Up and Push Fors Down

· 01:33

|

Welcome to Code Corner. Today, we’re diving into two simple rules of thumb from matklad’s latest post: “Push Ifs Up” and “Push Fors Down.”

First, “Push Ifs Up.” If your function starts with an if check, consider moving that check to the caller. Instead of

fn frobnicate(walrus: Option<Walrus>) { … }

you’d require a Walrus up front. As matklad puts it, “control flow and ifs are complicated, and are a source of bugs.” By centralizing branching in one place, you spot dead conditions and redundant logic faster—what he calls the “dissolving enum” refactor.

Next, “Push Fors Down,” from the data-oriented school. Rather than looping over each item,

for walrus in walruses {
  frobnicate(walrus)
}

introduce a batch operation:

frobnicate_batch(walruses)

Because “few things are few, many things are many,” batch APIs unlock vectorization, amortize startup costs, and often massively boost performance.

Best of all, these rules compose. Move your if outside the loop to avoid re-evaluating conditions in hot paths. In matklad’s words: “remove a branch from the hot loop, and potentially unlock vectorization.” That’s it—push the ifs up, push the fors down. Thanks for listening!
Link to Article


Subscribe

Listen to jawbreaker.io using one of many popular podcasting apps or directories.

Apple Podcasts Spotify Overcast Pocket Casts Amazon Music
← Previous · All Episodes · Next →