php - PHP 中的代码循环优化

标签 php optimization

有什么办法可以优化这段代码使其工作得更快?如果有任何建议,我将不胜感激!

这段代码在图创建过程中处理边的传输。

foreach($times_arrival as $city_id => $time_points) {
// if city is not prohibited for transfers and there is and exists any departure times for this city
if (isset($times_departure[$city_id]) && isset($cities[$city_id]))
{
    foreach($times_arrival[$city_id] as $t1_info) 
    {
        foreach($times_departure[$city_id] as $t2_info) 
        {
            if ($t1_info[0] != $t2_info[0]) //transfers are allowed only for different passages
            {
                $t1 = $t1_info[1];
                $t2 = $t2_info[1];

                $vertex_key = new Vertex($city_id, $t1, 1);
                $vertex_key = $vertex_key->toString();

                //minimum transfer time is 10 min.
                if (date('H:i', strtotime($t2)) > date('H:i', strtotime('+ 10 minutes', strtotime($t1))))
                {
                    $this->graph[$vertex_key][] = new Edge(
                        NULL,
                        $vertex_key, 
                        new Vertex($city_id, $t2, 0),
                        (float) 0,
                        $f((strtotime($t2) - strtotime($t1)) / 60, 0, 1) //edge weight
                    );
                }
                //if transfer is on the bound of the twenty-four hours
                else if (date('H:i', strtotime('+ 24 hours', strtotime($t2))) > date('H:i', strtotime('+ 10 minutes', strtotime($t1))))
                {
                    $this->graph[$vertex_key][] = new Edge(
                        NULL, 
                        $vertex_key,
                        new Vertex($city_id, $t2, 0),
                        (float) 0,
                        $f(strtotime('+ 24 hours', strtotime($t2)) - strtotime($t1) / 60, 0, 1) //edge weight
                    );
                }
            }
        }
    }
}
}

变量示例:

var_dump($times_arrival); //$times_departure have the same structure
array
  3 => 
    array
      0 => 
        array
          0 => string '1' (length=1)
          1 => string '08:12' (length=5)
      1 => 
        array
          0 => string '2' (length=1)
          1 => string '08:40' (length=5)
  41 => 
    array
      0 => 
        array
          0 => string '21' (length=2)
          1 => string '12:40' (length=5)

最佳答案

谢谢大家! 速度慢的原因是因为使用函数 strtotime()date()

关于php - PHP 中的代码循环优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10110617/

相关文章:

php - 在 Laravel 中批量更新每行的特定条件

php - 如何在 echo 中格式化字体样式和颜色

php - PHP 如何从两个数组中获取相同的值?

php - 在 PHP 中,是否可以使用字符串设置变量名?

asp.net - ASP.net 的运行时页面优化器 - 有什么意见吗?

ruby - 优化此 ruby​​ 代码

php - libphp7.so 需要 12.0.0 或更高版本

php - SQL需要提高运行速度

c - 如何优化此功能? (使用几乎所有的处理能力)

c# - Windows API 似乎比 BinaryWriter 快得多 - 我的测试正确吗?