What are the advantages of using multiple game loops instead of one?

Assume Level1, Level2, Level3. These levels may bring totally different problems and needs and they may also be completely separate, perhaps like a classic Mario game. One level needs multiple frame counters yet the others need none. Would it make sense to structure a game like that, with many loops?

I've written an implementation of this, which was actually my first loop design for my game, and memory management looks like few necessary global with many local variables, at the cost of less automated code (meaning more writing).

Is this done at all and if so, is this common?


1 Answer 1


The cost of rewriting your loop is not worth any perceived benefits of having "more efficient" loops that leave out unneeded bits.

This is "premature optimization". I would not consider multiple loops unless

  1. A profiler tells you the code in the loop is causing bottlenecks (very unlikey)
  2. Your levels are so different from one another that shared code is minimal
  • 4
    \$\begingroup\$ Re: 2, even if the shared code is minimal, I'd still recommend using a single loop with swappable "guts" - like a Strategy pattern or Execute-Around pattern - so even that minimal glue lives in a single place. Duplicating that code for each level would be planting land mines for any future changes. Forget to update just one, or update it incorrectly, and you've introduced a subtle bug that won't show up in most tests. \$\endgroup\$
    – DMGregory
    Aug 6, 2021 at 19:24
  • \$\begingroup\$ The "rewriting your loop" point makes using one loop compelling. The problem is that I'd still have a giant memory problem because I'd have to use lots of generically named globals, passed through the preprocessor, and perhaps put variables to the heap, which makes this choice actually hard. The "unneeded bits" are not an issue as there really aren't any. \$\endgroup\$
    – user154928
    Aug 6, 2021 at 21:15
  • 2
    \$\begingroup\$ @senatorsteven "memory problem" do you think you'll hit the RAM limit anytime soon? \$\endgroup\$
    – Vaillancourt
    Aug 7, 2021 at 0:41
  • 1
    \$\begingroup\$ Is the profiler telling you that you have RAM issues? \$\endgroup\$
    – Almo
    Aug 7, 2021 at 1:07

You must log in to answer this question.