Why while loop is faster than for loop




















Pros: If the number of iterations is not known up front, then this is a case where a for loop can't be used. The while loop is quite simple. It contains no indices or defined variables, so it is convenient when a loop is simply needed to keep performing an action until a desired condition is or isn't met.

Cons: Here is a big warning: When using a while loop, you need to make sure that the condition is actually going to turn false at some point in time. If the condition is always true, then you will end up in an infinite loop. A while loop is quite inefficient in IDL see example below. Efficiency, and While vs For When iterating through an array, here is a comparison of For vs. Repeat The repeat loop is very similar to the while loop in that it performs an indefinite number of iterations.

Pros: It turns out that Repeat is actually quite a bit more efficient than While, demonstrated below. Repeat may have the convenience that in many situations, the condition is not known or even defined until inside the loop.

For this reason, while loops often need the condition set to a dummy state, which must evaluate to true. Cons: Just like with a while loop, it is possible to end up in an infinite loop, so it is very important to make sure the end condition will always be met eventually. If the condition prior to the loop actually does matter i. However, the easy way around this is to simply put the entire loop inside a conditional statement. As others have said, any compiler worth its salt will generate practically identical code.

Any difference in performance is negligible - you are micro-optimizing. The real question is, what is more readable? And that's the for loop at least IMHO. If that were a C program, I would say neither. The compiler will output exactly the same code. Since it's not, I say measure it. Really though, it's not about which loop construct is faster, since that's a miniscule amount of time savings. It's about which loop construct is easier to maintain.

In the case you showed, a for loop is more appropriate because it's what other programmers including future you, hopefully will expect to see there. Do it for both codes, what ever one has the lowest milliseconds it runs faster. You might want to run the test multiple times and average them out to reduce the likelihood of background processes influencing the test.

You are likely to get really similar times on both of them, but I am interested to see if one is always just slightly faster. I used a for and while loop on a solid test machine no non-standard 3rd party background processes running. The test is was run consecutively 10 times, with 1 run timed out for milliseconds before execution:. A separate test I have conducted is located below, which implements 2 differently written factorial algorithms, 1 using a for loop, the other using a while loop.

Conclusion: No matter the sample size or specific task type tested, there is no clear winner in terms of performance between a while and for loop. As for infinite loops for ;; loop is better than while 1 since while evaluates every time the condition but again it depends on the compiler. They should be equal. Some optimizing compilers will be able to do better loop unrolling with a for loop, but odds are that if you're doing something that can be unrolled, a compiler smart enough to unroll it is probably also smart enough to interpret the loop condition of your while loop as something it can unroll as well.

Depends on the language and most likely its compiler, but they should be equivalent in most languages. It shouldn't matter which is faster. If it does matter then benchmark it using your real code and see for yourself. The answers to this other question might be useful as well: How to write more efficient code. Most compiler will compile to the exact same executable code for example in CIL. NET they definitely do. Either way, the body of the loop is where the processing time will be spent not the way you iterate.

Also when it comes to for loops. If you plan to only retrieve data and never modify data you should use a foreach. If you require the actual indexes for some reason you'll need to increment so you should use the regular for loop. I was wondering the same thing so i googled and ended up here. I did a small test in python extremely simple just to see and this is what I got:.

I also tried to benchmark the different kinds of loop in C. I used the same code as Shane , but I also tried with a do-while and found it to be the fastest. Syntax of a For Loop The initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. The test expression is the condition until when the loop is repeated.

Update statement is usually the number by which the loop variable is incremented. Which loop is faster in Java? No, changing the type of loop wouldn't matter. The only thing that can make it faster would be to have less nesting of loops, and looping over less values. The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all. Is Python really that slow? Having said that, as a dynamic language Python will typically perform slower for specific benchmarks than standard implementations of some other languages although it is faster than plenty of others.

As a dynamic language a lot of information about the program can only be determined at runtime. Which is more efficient for or while? Many times it comes down to programmer preference, or is reliant on efficiency. Generally, the for loop can be more efficient than the while loop, but not always. The idea of the While loop is: While something is the case, do the following block of code. Is Numpy slow? The loop will stop after testing the value wolf.

This means that the loop will not print the wolf in the console. Example 2 Break a while loop when the loop value is 3. The while loop will stop when the loop value is equal to 3.

Unlike For loop, the breakpoint value 3 will be included in the log message before the iteration stops. While loop executes a statement only when the condition is true.

A continue statement break a loop, check a specified condition and then proceed to the next iteration until the loop condition expression returns false. The loop skips a value specified in the continue statement condition. For example, to loop over some numbers and get the even numbers, we need a continue statement to break the loop whenever we iterate odd numbers.

Every time i iterates, it will check the value and if the value is an odd number, the loop will break and test the next value. A label identifies a loop. A label statement can be added inside a loop as an identifier to interrupt the iteration execution. These statements are called labels. These labels can then be used to refer to the code snippets later on. For instance, to add a myloop label to a loop block, add a semicolon to the end of the label name as shown below. The myloop statement can be used to refer to our code later on.

For example whenever a break or continue statements are needed. The code above results nothing different, as the results will be the same as when no label was used. In loops, labels come into play when using nested loops to specify the loop to be altered.

The label will determine exactly which loop to break or allow to continue. To get the best results, we will use different test methods. The results are quite eye-catching with while , do-while , and for comparatively faster. To get a clear picture and more desirable result to try to increase the number of iterations.

As the number of iterations increases, the results become quite comparable, and again the old for loop is giving stiff competition to the while and do-while loops. On the other hand, for of loop seems to lag behind. Created a separate code block because the nested loop creates performance overhead as the number of iterations increases.



0コメント

  • 1000 / 1000