4 ms·
It's not usually needed (especially these days), but there are times that it is better to repeat every possible iteration by hand and not have a loop. This is
by bigtunacan 4y ago
It's not usually needed (especially these days), but there are times that it is better to repeat every possible iteration by hand and not have a loop.
This is a technique called loop unrolling. It is done for performance reasons. This is something we used to do at a company working on games for the old feature phones (think Nokia 30/40/60 series stuff). The devices were very limited, there is no direct control over J2ME garbage collection, etc... so loops could very noticeably slow down games.
We initially wrote code with loops, then would performance test and manually unroll when it was necessary. Eventually this became very burdensome and we eventually... wrote code to unroll the loops for us and that code of course had loops in it because it was build code that wouldn't ship.
There are other performance situations where this technique applies.
This may not have been the situation there, but I think it's important that rather than assume stupidity from the outside that we try to ask why.
- 988747 4y agoLoop unrolling seems like something that should be done by a compiler when you turn on aggressive optimization flags, and not something you need to code explicitly.
- HWR_14 4y agoNow, that's probably true. However, in the days of feature phones compilers auto optimization were still inferior to a person unrolling a loop in ASM.
- bigtunacan 4y agoThat is why I said it's usually not needed, "especially these days". This was not true at the time. Relying on primitive compilers, especially the likes of the J2ME garbage collection would lead to total freezes in a game from something as simple as a loop. As the garbage collector decides previous passes in the loop are no longer needed it can trigger a garbage collection sweep. With such a slow and limited device a garbage collection sweep would literally cause a game to freeze until the sweep completed which could take on the order of several seconds. The loop unrolling was just one example of how we would go about preventing an undesirable sweep. As another example a large global game object array would be created when a game was started. As objects were created and deleted they would really just update pre-created objects in that array. This allowed us to prevent garbage collection, while simultaneously making sure we didn't run out of memory. The Nokia 1618 (a series 40 device) has a heap limit of 1024KB. Many S20 and S30 devices were even further memory constrained.