0

我在 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消耗这么多?

4

3 回答 3

1

This could be faster, try it:

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

There is a small difference when using array_key_exists() and isset(). Look in to the manual.

于 2012-07-11T22:56:40.970 回答
0

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

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需要在它上面做一些内部的魔法。

于 2012-07-11T23:12:55.753 回答
0

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

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;
}

这应该能解开谜团;)

于 2012-07-11T23:31:11.810 回答