Santosh S
Santosh S

Reputation: 4345

What is an alternate solution to nested multiple FOR loops?

It is always recommended to avoid multiple and nested for loops in your programming. But there are some cases where we have to use it. Is there any solution ("good practice" or design pattern) with which we can achieve the same result by reducing the computation time.

I would like to know a generic optimized logic which will replace multiple and nested for loop.

Note: This is not specific to any programming language.

Upvotes: 0

Views: 891

Answers (2)

Piotr Czarnecki
Piotr Czarnecki

Reputation: 1688

It's hard to answer without any specific example of situation I think, but some languages offer you for example parallel loops, so many threads can make some work in loop. Also simple refactoring is a good option - I mean seperate your loops in different methods.

Upvotes: 1

Michel Keijzers
Michel Keijzers

Reputation: 15367

What I normally do is using one loop per function, i.e. split multiple for loops into multiple functions, each performing one loop, e.g. (pseudo language):

execute_boxes(Boxes boxes)
   for each box in boxes:
      execute_box(box)

execute_box(Box box)
    for each side in box:
        ...

Upvotes: 2

Related Questions