[Lookin' for advice] How should I use loop effectively?

twitter logo ・1 min read

The reason why I raise the question because I feel like I'm abusing loop to solve various problems, such as: sorting, accessing data from arrays, searching, etc. Since I have see other real code do, I wonder how many loops are usually used in a program. Also, how other developers using loop in their algorithms/programs. What is frequency of loop in a small piece of code?

twitter logo DISCUSS (5)
markdown guide

Loops are useful and common, and in most cases are fine. Performance comes down to big-O notation most of the time, and a loop is O(n), which is perfectly acceptable performance in most cases.

What you want to avoid are nested loops, whenever possible, as those are usually O(n^2) or worse. There are, again, cases where a nested loop has a place, but use them sparingly and with great caution.

For any given problem, however, there may be more efficient ways of doing things. You'll need to research means of optimizing that particular solution. It helps to make yourself familiar with common design patterns, data structures, and algorithms, so you can better decide when to use a loop, and when to use something else.

All in all, it's on a case-by-case basis. There's no one-size-fits-all answer here.


sorting, accessing data from arrays, searching

Depending on the language, there's usually native functionality for this sort of stuff. You'll find a .sort() and the such.

Perhaps its an issue of reaching for what you know you can do yourself rather than looking up what the coding environment offers?

I'd guess that the lower level you get, the more loops you write because computers do a lot of looping.

What's an example of some code where you use a loop and you're not sure if there is another way to go about it?


It is my preference for using map, filter, and reduce. It allows me to extract the logic into testable and reusable functions.

Whatever language you are using should also contain sort, which will most times be faster than your custom rolled sorting algorithm.


If you use JavaScript, you can take a look at this benchmark to compare performance between different type of loops (for iterating in an array): jsperf.com/for-test-cases/1

The for..in method should not be used for arrays, but included for wholeness.


You’re not doing anything wrong by using loops for these things.

Classic DEV Post from Jan 18

Sh*tpost: can we stop saying "syntactic sugar"?

What does it actually mean? you're not helping!

Đăng Tú profile image
I'm ME! Surprise!