QB64 Phoenix Edition
Today I learned loops are slow - Printable Version

+- QB64 Phoenix Edition (https://qb64phoenix.com/forum)
+-- Forum: QB64 Rising (https://qb64phoenix.com/forum/forumdisplay.php?fid=1)
+--- Forum: Code and Stuff (https://qb64phoenix.com/forum/forumdisplay.php?fid=3)
+---- Forum: Programs (https://qb64phoenix.com/forum/forumdisplay.php?fid=7)
+---- Thread: Today I learned loops are slow (/showthread.php?tid=4159)

Pages: 1 2


RE: Today I learned loops are slow - TDarcos - 12-20-2025

We (as programmers) already have a term for when something takes a long time. Even on a computer you own and are simply programming for pleasure. The term is "expensive operation." The reason is, at the machine code level, some operations take more time to execute, e.g. adding two numbers is "less expensive" than calculating a square root. So often programmers will find workarounds. Like dividing by a power of 2, e.g. 4,8,16,32, etc. Division is a very expensive operation. But shifting something one or more bits left or right is much cheaper by comparison. If you have a program where several million calculations have to be done, shifting an integer 1 bit right is the same as dividing by 2. Some compilers check, and when possible, substitute shift left or right for some multiplication or division operation, respectively.

Looping is another one of those expensive operations because of the set-up at the start of the loop and the process on each iteration. There are tricks that compiler writers use, such as if a loop will have a relatively small number of repetitions, that not doing the loop is cheaper, at a small increase in code size, the compiler will "unroll" the loop and repeat the instructions used in the loop inline, repeating the number of times it would have looped. Sometimes the "savings" are amazing, code runs twice as fast. Or maybe you don't get that much improvement, maybe you only get 10%, but on large operations (e.g. the multi-million or multi-billion calculation example) the savings can be significant.