【问题标题】:php. why function's running time is big?php。为什么函数的运行时间很大?
【发布时间】:2012-07-11 22:52:24
【问题描述】:

我在 php 中分析我的代码。问题是关于下一个功能:

// returns true if edge exists in the tree
protected function edgeExist( $srcNodeId, $firstToken ) {
    $result = array_key_exists( $srcNodeId, $this->edges )
              && array_key_exists( $firstToken, $this->edges[$srcNodeId]);
    return $result;
}

根据分析器,函数 edgeExist 消耗大约 10% 的运行时间,但函数 array_key_exists 消耗大约 0.2% 的运行时间。 为什么函数edgeExist 消耗这么多?

【问题讨论】:

  • 尝试使用isset,它可能array_key_exists快。例如$result = isset($srcNodeId[$this->edges]) && isset($firstToken[$this->$this->edges[$srcNodeId]]);.
  • 但无论如何array_key_exists 已经足够快了,它消耗了 0.2% 的运行时间。我不明白为什么edgeExist 消耗这么多。

标签: php profiling


【解决方案1】:

这可能更快,试试吧:

protected function edgeExist( $srcNodeId, $firstToken ) {
    return isset($this->edges[$srcNodeId][$firstToken]);
}

使用array_key_exists()isset() 时存在细微差别。看说明书。

【讨论】:

    【解决方案2】:

    您可以尝试比较个人资料结果

    protected function edgeExist( $srcNodeId, $firstToken ) {
        $result = array_key_exists( $firstToken, array());
        return $result;
    }
    

    protected function edgeExist( $srcNodeId, $firstToken ) {
        $result = array_key_exists( $firstToken, $this->edges[$srcNodeId]);
        return $result;
    }
    

    我想也许 $this->edges[$srcNodeId] 是一个巨大的数组,php 需要对其进行一些内部魔法。

    【讨论】:

    • 我不知道怎么做,因为它会弄乱程序的逻辑,它不会运行
    • 我不明白你搞乱逻辑的问题,我希望你没有处于生产模式;)。没关系,如果您不想更改 edgeExist,那么您可以添加 2 个新方法 edgeExist2、edgeExist3 然后调用它们并忽略返回的结果。
    【解决方案3】:

    您可以通过以下方式测量每个部分的运行时间:

    protected function edgeExist( $srcNodeId, $firstToken ) {
        $time = microtime();
        $result1 = array_key_exists( $srcNodeId, $this->edges )
        $time2 = microtime();
        $result2 = array_key_exists( $firstToken, $this->edges[$srcNodeId]);
        $time3 = microtime();
        $result = $result1 && $result2;
        $time4 = microtime();
        echo "calculating the first result took " . $time2 - $time1 . " microseconds\n".
        echo "calculating the second result took " . $time3 - $time2 . " microseconds\n".
        echo "calculating the && took " . $time4 - $time3 . " microseconds\n".
        return $result;
    }
    

    这应该能解开谜团;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多