php - 虽然每个都已弃用,但 Foreach 替换需要更多时间

标签 php performance foreach while-loop each

在 PHP 7.2 中,each 已被弃用。 The documentation说:

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

我正在努力调整电子商务应用程序并将所有 while-each 循环转换为(据称)等效的 foreach

正如您在下面看到的,我已经用等效的 foreach 替换了所有 resetwhile 循环。

大部分情况下都运行良好。然而,我们有一位顾客,她的购物车里有很长的商品 list ,她试图结帐,并提示她从服务器收到错误 502。 我尝试重现该情况,发现只有她的购物车失败,结帐页面加载需要 2 分钟以上,然后出现 502 错误。 然后我开始调试我最近修改的很多文件,反复试验,直到我发现问题出在这个特定的文件和特定的函数上。 每当我将第一个 foreach 循环切换回 while 循环时,客户可以在不到一秒的时间内加载结账页面。切换回 foreach - 再次需要几分钟,但 php 在结束执行之前超时。

当然,我确实对 foreachwhile 循环的输出进行了测试(var_dump $products_id$this ->contents 例如),它们看起来都相同。我已经重写了代码以使其顺利工作并保持 PHP 7.2 兼容,但我仍然不明白为什么会发生这种情况。

这是完整的功能:

function get_content_type() {
  $this->content_type = false;

  if ( (DOWNLOAD_ENABLED == 'true') && ($this->count_contents() > 0) ) {

    // reset($this->contents);
    // while (list($products_id, ) = each($this->contents)) {
    foreach(array_keys($this->contents) as $products_id) {

      if (isset($this->contents[$products_id]['attributes'])) {
        // reset($this->contents[$products_id]['attributes']);
        // while (list(, $value) = each($this->contents[$products_id]['attributes'])) {
        foreach ($this->contents[$products_id]['attributes'] as $value) {
          $virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad where pa.products_id = '" . (int)$products_id . "' and pa.options_values_id = '" . (int)$value . "' and pa.products_attributes_id = pad.products_attributes_id");
          $virtual_check = tep_db_fetch_array($virtual_check_query);

          if ($virtual_check['total'] > 0) {
            switch ($this->content_type) {
              case 'physical':
                $this->content_type = 'mixed';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'virtual';
                break;
            }
          } else {
            switch ($this->content_type) {
              case 'virtual':
                $this->content_type = 'mixed';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'physical';
                break;
            }
          }
        }

      } elseif ($this->show_weight() == 0) {
      // reset($this->contents);  
      //  while (list($products_id, ) = each($this->contents)) { 
        foreach (array_keys($this->contents) as $products_id) {
          $virtual_check_query = tep_db_query("select products_weight from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'");
          $virtual_check = tep_db_fetch_array($virtual_check_query);
          if ($virtual_check['products_weight'] == 0) {
            switch ($this->content_type) {
              case 'physical':
                $this->content_type = 'mixed';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'virtual';
                break;
            }
          } else {
            switch ($this->content_type) {
              case 'virtual':
                $this->content_type = 'mixed';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'physical';
                break;
            }
          }
        }

      } else {
        switch ($this->content_type) {
          case 'virtual':
            $this->content_type = 'mixed';

            return $this->content_type;
            break;
          default:
            $this->content_type = 'physical';
            break;
        }
      }
    }
  } else {
    $this->content_type = 'physical';
  }

  return $this->content_type;
}

谢谢

编辑:这是数组: https://pastebin.com/VawX3XpW

该问题已在我尝试过的所有配置上进行了测试并重现:

1) 高端 Windows 10 电脑 + WAMP (Apache 2.4 + MariaDB 10.2 + PHP 5.6+/7+/7.1+/7.2+)

2) 高端 CentOS/cPanel 服务器 + Litespeed + MariaDB 10.1 + PHP 5.6+

只是强调一下,我不想重写代码或模拟each然后重写代码,因为我们不会从中学到太多东西。我只是想找到一个合乎逻辑的解释或解决/调试这个谜团的方法。也许某个地方的某个人曾经遇到过这样的问题,并且可以对此做出一些说明。

2018 年 8 月 1 日更新

我已经尝试调试这个好几天了,最终发现了一些有趣的事情。我在第一个 foreach 循环和 while 循环上添加了“echo point”和 exit,如下所示:

function get_content_type() {
  $this->content_type = false;

  if ( (DOWNLOAD_ENABLED == 'true') && ($this->count_contents() > 0) ) {

    // reset($this->contents);
    // while (list($products_id, ) = each($this->contents)) { echo '1 ';
    foreach(array_keys($this->contents) as $products_id) { echo '1 ';

      if (isset($this->contents[$products_id]['attributes'])) { echo '2 ';
        // reset($this->contents[$products_id]['attributes']);
        // while (list(, $value) = each($this->contents[$products_id]['attributes'])) {
        foreach ($this->contents[$products_id]['attributes'] as $value) { echo '3 ';
          $virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad where pa.products_id = '" . (int)$products_id . "' and pa.options_values_id = '" . (int)$value . "' and pa.products_attributes_id = pad.products_attributes_id");
          $virtual_check = tep_db_fetch_array($virtual_check_query);

          if ($virtual_check['total'] > 0) {
            switch ($this->content_type) {
              case 'physical':
                $this->content_type = 'mixed'; echo '4 ';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'virtual'; echo '5 ';
                break;
            }
          } else {
            switch ($this->content_type) {
              case 'virtual':
                $this->content_type = 'mixed'; echo '6 ';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'physical'; echo '7 ';
                break;
            }
          }
        }

      } elseif ($this->show_weight() == 0) {
      // reset($this->contents);  
      //  while (list($products_id, ) = each($this->contents)) { 
        foreach (array_keys($this->contents) as $products_id) {
          $virtual_check_query = tep_db_query("select products_weight from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'");
          $virtual_check = tep_db_fetch_array($virtual_check_query);
          if ($virtual_check['products_weight'] == 0) {
            switch ($this->content_type) {
              case 'physical':
                $this->content_type = 'mixed'; echo '8 ';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'virtual'; echo '9 ';
                break;
            }
          } else {
            switch ($this->content_type) {
              case 'virtual':
                $this->content_type = 'mixed'; echo '10 ';

                return $this->content_type;
                break;
              default:
                $this->content_type = 'physical'; echo '11 ';
                break;
            }
          }
        }

      } else {
        switch ($this->content_type) {
          case 'virtual':
            $this->content_type = 'mixed'; echo '12 ';

            return $this->content_type;
            break;
          default:
            $this->content_type = 'physical'; echo '13 ';
            break;
        }
      }
    } exit; //Exiting from the loop to check output
  } else {
    $this->content_type = 'physical';
  }

  return $this->content_type;
}

当我使用 while 运行循环时,我得到的输出只是“1 13”一次,这意味着循环仅运行一次并停止。 但是,当我将其更改为 foreach 时,我得到了一长串“1 13 1 13 1 13...”,这意味着它循环了很多次。我已经进一步调查了 while 循环和 foreach 循环的 breaks 之间是否有任何区别,但我仍然找不到任何支持信息。然后我将最后一个 break; 重写为 break 2; 并再次测试了 foreach ,这次它似乎只运行了一次,就像它是一个带有 break;while 循环(不是 break 2;) 编辑:只是为了澄清 - while break 和 foreach break 之间没有区别。它们的工作方式相同。

更新#2: 我已将 } elseif ($this->show_weight() == 0) { 修改为 } elseif (2 == 0) {while 循环现在运行的次数与 foreach 循环一样多。 var_dump($this->show_weight()); 结果 float 4466.54。 这个问题对我来说仍然没有任何意义。

再次感谢

最佳答案

这实际上是一个非常简单的算法问题,它与以下事实有关:当 show_weight()0 时,您正在循环相同 数组(编辑:根据您的评论,show_weight() 本身循环相同的数组)。

TL;DR 使用 while 时,所有这些循环都共享相同的内部指针并相互影响。对于foreach,每个循环都是独立的,因此它会运行更多的迭代,从而产生性能问题。

一个例子抵得上一千个字,希望下面的代码能让事情变得更清楚:

<?php

$array = ['foo','bar','baz'];

foreach ( array_keys($array) as $key ) {
    echo $array[$key],"\n";
    foreach ( array_keys($array) as $key ) {
        echo "\t",$array[$key],"\n";
    }
}

echo "---------------\n";

while ( list($key,) = each($array) ) {
    echo $array[$key],"\n";
    reset($array);
    while ( list($key,) = each($array) ) {
        echo "\t",$array[$key],"\n";
    }
}

这将输出:

foo
        foo
        bar
        baz
bar
        foo
        bar
        baz
baz
        foo
        bar
        baz
---------------
foo
        foo
        bar
        baz

如您所见,对于大小为 3 的数组,foreach 需要 3² 次迭代,而 while 只需 3 次迭代。这就是性能问题。

为什么 while 更快?

因为在第二个(内部)while 的末尾,$array 的内部指针将指向数组的末尾,因此第一个 (外部)while 就会停止。

使用 foreach,由于您使用的是对 array_keys 的 2 个不同调用的结果,因此您使用的是 2 个不共享相同内部指针的不同数组,因此循环没有理由停止。在第二个(内部)foreach 之后简单的 return 应该可以解决问题。

关于php - 虽然每个都已弃用,但 Foreach 替换需要更多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390249/

相关文章:

javascript - 由 window.location.href 调用时 SQL 查询不起作用

performance - perl 中的哈希元素的别名

performance - 在这个 Common Lisp 函数中消除 "mystery-consing"?

php - 如何显示mysql中每个唯一项目的信息,合并每个项目的信息

使用 yacc 或 Bison 和 Flex 创建 foreach 关键字

php - 长轮询/HTTP流一般问题

php - 使用 MySQLi 列出数据库中的所有表

php - CakePHP 2.0 帐户验证

c++ - 为什么 endl 被用作 "\n"的同义词,即使它会导致显着的性能损失?

java - java中的对象不断更新循环对象