Comparison of foreach and while loops in php _ PHP Tutorial

Source: Internet
Author: User
Comparison of foreach and while loops in php. Foreach and while are both loops in php, so what is their difference between foreach and while loops, and that performance will be better, next, I will introduce the differences between foreach and while loops and that between foreach and while loops in php. what is the difference between foreach and while loops and the performance will be better, next, I will introduce the differences between foreach and while loops and the comparison of performance. 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:

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:

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:
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:
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:

/*
* @ 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)

';
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)

';

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)

';
######################################

?>

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.

...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.