


Differences and performance comparison between foreach and while loops
foreach and while both loop in php, so what is the difference between foreach and while loop? Which one will have better performance? Let me introduce to you the difference between foreach and while loop. Performance comparison.
In a while loop, Perl will read a line of input, store it in a variable and execute the loop body. Then, it goes back to find other input lines.
In the foreach loop, the entire line of input operator will be executed in the list context (because foreach needs to process the contents of the list line by line). Before the loop can start executing, it must read all the input.
When inputting large-capacity files, using foreach will occupy a lot of memory. The difference between the two will be very obvious. Therefore, the best approach is usually to use the abbreviation of while loop and let it process one line at a time.
When you want to repeatedly execute certain statements or paragraphs, C# provides 4 different loop statement options for you to use according to different current tasks:
. for statement
. foreach statement
. while statement
. do statement
1.for
The for statement is particularly useful when you know in advance how many times an contained statement should be executed. The regular syntax allows an enclosed statement (and loop expression) to be executed repeatedly when a condition is true:
for (initialization; condition; loop) enclosed statement
Please note that initialization, conditions and loops are optional. If you omit the condition, you can create an infinite loop that requires a jump statement (break or goto) to exit.
for (;;) { break; // 由于某些原因 }
Another important point is that you can add multiple comma-separated statements to all three parameters of the for loop at the same time. For example, you can initialize two variables, have three conditionals, and repeat 4 variables.
2.foreach
One feature that has existed in the Visual Basic language for a long time is the collection of enumerations by using the For Each statement. C# also has a command for collecting enumerations through the foreach statement:
foreach (type identifier in expression) containing statement
The loop variable is declared by the type and identifier, and Expressions correspond to collections. The loop variable represents the collection element for which the loop is running.
3.while
When you want to execute an included statement 0 or more times, the while statement is exactly what you want:
while (condition) INCLUDED STATEMENT
The conditional statement - which is also a Boolean expression - controls the number of times the included statement is executed. You can use break and continue statements to control the execution of statements in a while statement, which operates in exactly the same way as in a for statement.
4,do
C#The last available loop statement is the do statement. It is very similar to a while statement in that the condition is verified only after the initial loop.
do { 内含语句 } while (条件);
The do statement guarantees that the contained statements have been executed at least once, and they continue to be executed as long as the condition evaluates to true. By using the break statement, you can force execution to exit the do block. If you want to skip this loop, use the continue statement.
Performance comparison
foreach operates on a copy of the array (by copying the array), while while operates by moving the internal index of the array. Under general logic, it is believed that while should be faster than foreach (because foreach first copies the array when it starts executing, while while directly moves the internal pointer), but the result is just the opposite.
In the loop, the array "read" operation is performed, so foreach is faster than while:
foreach ($array as $value) { echo $value; } while (list($key) = each($array)) { echo $array[$key]; }
In the loop, the array "write" operation is performed, then while is faster than foreach:
foreach ($array as $key => $value) { echo $array[$key] = $value . '...'; } while (list($key) = each($array)) { $array[$key] = $array[$key] . '...'; }
Let us first test the time it takes to traverse a one-dimensional array with 50,000 subscripts:
<?php /* * @ Author: Lilov * @ Homepage: www.111cn.net * @ E-mail: zhongjiechao@gmail.com * */ $arr = array(); for($i = 0; $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><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><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><br>'; ###################################### ?>
Test results:
will be three times Average the test results:
corresponds 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 The fastest one is while. The slowest one is while. foreach is about 20% ~ 30% faster than while. Then add the array subscript to 500000 and 5000000 and the test result is the same. But from a principle point of view, foreach operates on a copy of the array (by copying the array), while while operates by moving the internal index of the array. Generally speaking, it is believed that while should be faster than foreach (because foreach first executes the The array is copied in, while while moves the internal pointer directly), but the result is just the opposite. The reason should be that foreach is an internal implementation of PHP, while while is a general loop structure.
The above is the detailed content of Differences and performance comparison between foreach and while loops. For more information, please follow other related articles on the PHP Chinese website!

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!