Categories: PHP编程

PHP FOR vs FOREACH性能比较

“foreach”比“for”慢。foreach复制需要执行迭代的数组。为了提高性能,需要使用引用的概念。除此之外,“foreach”也很容易使用。

例子

<?php
   $my_arr = array();
   for ($i = 0; $i < 10000; $i++) {
      $my_arr[] = $i;
   }
   $start = microtime(true);
   foreach ($my_arr as $k => $v) {
      $my_arr[$k] = $v + 1;
   }
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => &$v) {
      $v = $v + 1;
   }
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => $v) {}
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => &$v) {}
   echo "This completed in ", microtime(true) - $start, " seconds";
?>

结果

This completed in 0.00058293342590332 seconds
This completed in 0.00063300132751465 seconds
This completed in 0.00023412704467773 seconds
This completed in 0.00026583671569824 seconds
5.0
01
如何在PHP中捕获var_dump到字符串的结果?
PHP错误处理指南
嘻嘻

嘻嘻IT: 笔者是一个工作七八年的程序猿老鸟,从事涉及的技术栈主要包括PHP、Linux、Devops等,喜欢研究新技术,尝试新技术,提升技术自动化和开发效率,致力于write less,do more! 技术每年都会层出不穷,领域划分的越来越细,不可能学习所有的东西,保持对技术的好奇心,理解技术中核心思想,做一个有深度,有思想的开发!

Share
Published by
嘻嘻

Recent Posts

全球货币导航网页上线了!

o在全球化的今天,货币兑换和国…

9小时 ago

bash字符串拼接

在编程中,字符串的拼接是一个非…

9小时 ago

Bash Case详解

Bash case 语句通常用…

10小时 ago

Bash for详解

for循环是编程语言中的基础概…

10小时 ago

liunux中你必须知道alias命令?

在Linux操作系统中,无论你…

1天 ago

zshrc文件详解

Zsh 是一个强大的 shel…

2天 ago