Home Backend Development PHP Tutorial Performance comparison of foreach, while and for_PHP tutorial

Performance comparison of foreach, while and for_PHP tutorial

Jul 13, 2016 pm 05:35 PM
for foreach while generally performance case array method Compare Traverse

Generally, there are three methods to traverse an array, for, while, and foreach. The simplest and most convenient of them is foreach. So what are the differences in operation and performance between them? Which method is usually better to use.
Let us first test the time it takes to traverse a one-dimensional array with 50,000 subscripts:

Test platform:
CPU: P-M 725
Memory: 512M
Hard disk: 40G 5400 rpm
OS: Windows XP SP2
WEB: apache 2.0.54 php5.0.4

Test code:
/*
* @ Author: Lilov
* @ Homepage: www.codesky.com
* @ E-mail: zhongjiechao@gmail .com
*
*/

$arr = array();
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}

function GetRunTime()
{
list($usec,$sec)=explode(" ",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:

Average the three 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 is the fastest, and the slowest is while. foreach is about 20% ~ 30% faster than while. Then increase the array subscript to 500000 and 5000000, and the test results are 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 places 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.

So, in general applications, I prefer to use the foreach form, which is simple and efficient. Under PHP5, foreach can also traverse the attributes of a class.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508306.htmlTechArticleGenerally, there are three methods to traverse an array, for, while, and foreach. The simplest and most convenient of them is foreach. So what is the difference between them in operation and performance? Usually use that...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Performance comparison of different Java frameworks Performance comparison of different Java frameworks Jun 05, 2024 pm 07:14 PM

Performance comparison of different Java frameworks: REST API request processing: Vert.x is the best, with a request rate of 2 times SpringBoot and 3 times Dropwizard. Database query: SpringBoot's HibernateORM is better than Vert.x and Dropwizard's ORM. Caching operations: Vert.x's Hazelcast client is superior to SpringBoot and Dropwizard's caching mechanisms. Suitable framework: Choose according to application requirements. Vert.x is suitable for high-performance web services, SpringBoot is suitable for data-intensive applications, and Dropwizard is suitable for microservice architecture.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

How to optimize the performance of multi-threaded programs in C++? How to optimize the performance of multi-threaded programs in C++? Jun 05, 2024 pm 02:04 PM

Effective techniques for optimizing C++ multi-threaded performance include limiting the number of threads to avoid resource contention. Use lightweight mutex locks to reduce contention. Optimize the scope of the lock and minimize the waiting time. Use lock-free data structures to improve concurrency. Avoid busy waiting and notify threads of resource availability through events.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

See all articles