+ 5

What can be used instead of for loops to reduce execution time ?

16th Jun 2018, 3:38 AM
Crystal!!!😎
Crystal!!!😎 - avatar
5 Answers
+ 2
Use for loop when number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known. Use while loops where exact number of iterations is not known but the loop termination condition is known. Use do while loop if the code needs to be executed at least once like in Menu driven programs
16th Jun 2018, 4:15 AM
Prakash
Prakash - avatar
+ 2
For, while, and do-while loops all have near identical performance in most languages. You can duplicate the exact behavior of while and do-while loops using a for loop. The only reason to use one of them over another is readability. The for-each loop is the one possible exception since depending on language and collection type, it might involve internally generating iterators.
16th Jun 2018, 4:36 AM
Shardis Wolfe
+ 1
while loop seems to be a bit faster than for loop in javascript
16th Jun 2018, 3:53 AM
wenz
wenz - avatar
+ 1
Give list comprehensions a try!
17th Jun 2018, 3:48 PM
Erik Samuelsson
Erik Samuelsson - avatar
+ 1
Short version: list comprehensions may or may not be faster than for-loop depending on problem specifics and feature implementation within chosen language. For those unaware of them, list comprehensions are a syntactic variation of loops primarily intended for creating new lists from existing lists. Within that problem scope, they are faster than a for-loop not because of inherent quality but because the implicit operation they use to append to the new list uses a faster implementation than the explicit append() function call used in an equivalent for-loop. If the problem does not involve looping to build a new list, list comprehensions may actually be slower than for-loop. Here is a good analysis comparing list comprehensions, for-loop, and some other methods for generating a single number from existing lists - https://stackoverflow.com/questions/28581218/speed-efficiency-comparison-for-loop-vs-list-comprehension-vs-other-methods
17th Jun 2018, 5:35 PM
Shardis Wolfe