search
HomeBackend DevelopmentPHP TutorialPHP中for和foreach哪个效率高一些?

PHP中for和foreach哪个效率高一些?

Jun 13, 2016 pm 12:00 PM
forforeachphp

PHP中for和foreach哪个效率高一些?

for和foreach那个效率高?原因是什么?

PHP中for和foreach效率高的是foreach

for循环遍历方法:

public function getForTime(){
    $big_Array = range(0,1000000,1);

     /* for循环遍历数组示例 */
    $start_For_Time = $this->microtime_float();
    //$array_Count = count($big_Array);
    for ($i=0;$i<count($big_Array);$i++) {
            $i;
    }
    $end_For_Time = $this->microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo &#39;for循环遍历耗时:&#39;.$for_Time.&#39;<br>&#39;;
}

foreach循环遍历方法:

public function getForeachTime(){
$big_Array = range(0,1000000,1);

 /* foreach循环遍历数组示例 */
    $start_Foreach_Time = $this->microtime_float();
    foreach ($big_Array as $key=>$val) {
            $key;
    }
    $end_Foreach_Time = $this->microtime_float();
    $foreach_Time = $end_Foreach_Time - $start_Foreach_Time;
    echo &#39;foreach循环遍历耗时:&#39;.$foreach_Time;
}

时间计算方法:

/**
 *  时间统计函数
 */
private function microtime_float($time = null)
{
   list($usec, $sec) = explode(&#39; &#39;, $time ? $time : microtime());
   return ((float)$usec + (float)$sec);
}

看一下两种方式耗时

/*
 * 输出结果:第一种情况:先count在for循环遍历耗时:0.028002023696899 秒
 *                         foreach循环遍历耗时:0.003000020980835 秒
 *        第二种情况:在for循环条件中做count遍历耗时:0.095005035400391 秒
 *                            foreach循环遍历耗时:0.0040009021759033 秒
 * */

从上面的测试中我们可以明显的得出两条结论:

1、for循环遍历的效率是低于foreach循环遍历

2、for循环在外部做count和在条件中做count相比较,第一种效率更高

效率高的原因是什么呢?在寻找这个答案之前我们先探讨原理分别是什么。

for 循环:

每次从$i开始,每次循环都需要判断$i是否小于count,这占用了很大一部分时间
小于继续,否则终止循环

foreach:

foreach 依赖 IEnumerable.

第一次 var a in GetList() 时 调用 GetEnumerator 返回第一个对象 并 赋给a,

以后每次再执行 var a in GetList() 的时候 调用 MoveNext.直到循环结束.

期间GetList()方法只执行一次.

从上面是分析我们明显可以得出结论:php 的foreach循环效率是大大高于for循环。也许有很大的一个原因是for 要进行很多次条件判断。所以以后能用foreach的地方就用foreach,可以提高1倍的效率。

BUT:事实真的是这样吗?有人会说这个例子已经很明显了啊,结论一目了然,难道还有其他的可能吗?

我觉得事实没这么简单,如果真的是这样,for循环存在的意义是什么呢?

既然foreach效率高于for这么多倍,就直接都用foreach不就行了吗?个人觉得我测试的这个例子有一定的局限性,并不能作为评估两个循环方式效率高低的绝对依据。

不过,对于我们phper来说,正常工作当中还是使用foreach循环遍历比较好,至于编译层是如何工作的没必要涉及太深,如果有兴趣可以深度研究一下。

更多相关知识,请访问 PHP中文网!!

Statement
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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

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.