Foreach and while are both loops in php, so what is the difference between foreach and while loops? The performance will be better. Next I will introduce the differences between foreach and while loops and the performance comparison, for more information, see.
In the while LOOP, Perl reads a row of input, stores it into a variable, and executes the loop body. Then, it looks back for other input rows.
In a foreach loop, the entire input operator is executed in the context of the List (because foreach needs to process the list content row by row ). Before the loop starts, it must read all the input.
When a large file is input, using foreach will occupy a large amount of memory. The difference between the two is very obvious. Therefore, the best practice is to try to use the while loop to process a row at a time.
Below are some materials:
When you want to execute some statements or segments repeatedly, C # provides four different loop statements based on the current task:
. For statement
. Foreach statement
. While statement
. Do statement
1.
The for statement is particularly useful when you know in advance how many times a containing statement should be executed. When the condition is true, the regular syntax allows repeated execution of containing statements (and loop expressions ):
For (initialization; condition; loop) contains statements
Note that initialization, conditions, and loops are optional. If the condition is ignored, you can generate an endless loop. You must use a jump Statement (break or goto) to exit.
The Code is as follows: |
Copy code |
For (;;) { Break; // for some reason } |
Another key point is that you can add multiple statements separated by commas to all three parameters of the for loop. For example, you can initialize two variables, have three condition statements, and repeat four variables.
2. foreach
One feature that has existed For a long time in Visual Basic is to collect enumerations by using the For Each statement. C # using the foreach statement, there is also a command for collecting enumeration:
Foreach (type identifier in expression) contains the statement
Cyclic variables are declared by types and identifiers, and expressions correspond to collection. Loop variables represent the collection elements for which the loop is running.
3. while
When you want to execute a containing statement 0 times or more times, the while statement is exactly what you want:
While (condition) containing statement
A Condition Statement, which is also a Boolean expression, controls the number of times a containing statement is executed. You can use the break and continue statements to control the execution statements in the while statement. The running method is the same as that in the for statement.
4, do
C # The last statement that can be used is the do statement. It is very similar to the while statement. The condition is verified only after the initial loop.
The Code is as follows: |
Copy code |
Do { Containing statements } While (condition ); |
Do statements ensure that the contained statements are executed at least once, and they are executed as long as the condition evaluate value is true. By using the break statement, you can force the running to exit the do block. If you want to skip this loop, use the continue statement.
Performance Comparison
Foreach performs operations on Array replicas (by copying arrays), while operations are performed by moving internal indicators of the array. Generally, it is logically considered that, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite.
If the array "read" operation is performed in a loop, foreach is faster than while:
The Code is as follows: |
Copy code |
Foreach ($ array as $ value ){ Echo $ value; } While (list ($ key) = each ($ array )){ Echo $ array [$ key]; } |
When the array "write" operation is performed in a loop, while is faster than foreach:
The Code is as follows: |
Copy code |
Foreach ($ array as $ key => $ value ){ Echo $ array [$ key] = $ value .'...'; } While (list ($ key) = each ($ array )){ $ Array [$ key] = $ array [$ key]. '...'; } |
Next, let's test the time it takes to traverse a one-dimensional array with 50000 subtopics:
Test Platform:
CPU: P-M 725
Memory: 512 MB
Hard Disk: 40 Gb 5400 rpm
OS: Windows xp SP2
WEB: apache 2.0.54 php5.0.4
Test code:
The Code is as follows: |
Copy code |
<? Php /* * @ Author: Lilov * @ Homepage: www. bKjia. c0m * @ E-mail: zhongjiechao@gmail.com * */ $ Arr = array (); For ($ I = 0; I I <50000; $ I ++ ){ $ Arr [] = $ I * rand (1000,9999 ); } Function GetRunTime () { List ($ usec, $ sec) = exp lode ("", microtime ()); Return (float) $ usec + (float) $ sec ); } ###################################### $ Time_start = GetRunTime (); For ($ I = 0; $ I <count ($ arr); $ I ++ ){ $ Str. = $ arr [$ I]; } $ Time_end = GetRunTime (); $ Time_used = $ time_end-$ time_start; Echo 'used time of for: '. round ($ time_used, 7).' (s) <br> '; Unset ($ str, $ time_start, $ time_end, $ time_used ); ###################################### $ Time_start = GetRunTime (); While (list ($ key, $ val) = each ($ arr )){ $ Str. = $ val; } $ Time_end = GetRunTime (); $ Time_used = $ time_end-$ time_start; Echo 'used time of while: '. round ($ time_used, 7).' (s) <br> '; Unset ($ str, $ key, $ val, $ time_start, $ time_end, $ time_used ); ###################################### $ Time_start = GetRunTime (); Foreach ($ arr as $ key => $ val ){ $ Str. = $ val; } $ Time_end = GetRunTime (); $ Time_used = $ time_end-$ time_start; Echo 'used time of foreach: '. round ($ time_used, 7).' (s) <br> '; ###################################### ?> |
Test results:
Calculate the average value of the three test results:
Corresponding to for, while, and foreach respectively
0.1311650
0.1666853
0.1237440
After repeated tests, the results show that for traversing the same array, foreach is the fastest, while is the slowest. Foreach is about 20% ~ Faster than while ~ About 30%. Then add the array subscript to the 500000 and 5000000 test results. However, in principle, foreach performs operations on the array copy (by copying the array), while moves the internal indicator of the array to perform operations, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite. The reason should be that foreach is implemented internally in PHP, while is a general loop structure.
Summary:Generally, foreach involves value replication, which is certainly slower than while, but in fact, if it is only in the loop to read the array, then foreach is very fast, this is because the replication mechanism adopted by PHP is "reference count, write copy". That is to say, even if a variable is copied in PHP, the initial form is basically still the reference form, real replication occurs only when the content of the variable changes. The reason for this is to save memory consumption and improve the replication efficiency. In this case, foreach's efficient read operations are not difficult to understand. In addition, since foreach is not suitable for array write operations, we can come up with a conclusion. In most cases, it is similar to foreach ($ array as $ key => $ value) the code used for array write operations should be replaced with while (list ($ key) = each ($ array )). The speed differences produced by these techniques may not be obvious in small projects, but in large projects like frameworks, a single request may involve hundreds of thousands of array loop operations, the difference is obviously magnified.