2012-07-11 23 views
0

我正在分析我的代码在php中。一个问题是关于未来的功能: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消耗这么多?使用array_key_exists()isset()

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

有一个小的差异:

+0

尝试使用'isset',它可以* *是不是'array_key_exists'更快。例如'$ result = isset($ srcNodeId [$ this-> edges])&& isset($ firstToken [$ this - > $ this-> edges [$ srcNodeId]]);'。 – 2012-07-11 22:54:27

+0

但无论如何'array_key_exists'足够快,它消耗0.2%的运行时间。我无法理解为什么'edgeExist'消耗这么多。 – ashim 2012-07-11 22:57:44

回答

1

这可能会更快,试试吧。查看手册。

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

我想也许这 - $>边缘轮廓比较结果[$ srcNodeId]是一些巨大的数组和PHP需要做一些内部的魔法在上面。

+0

我不知道该怎么做,因为它会搞乱程序的逻辑并且不会运行 – ashim 2012-07-11 23:23:41

+0

我不明白你搞乱逻辑的问题,我希望你不是在生产模式下)。没关系,如果你不想改变edgeExist,那么你可以添加2个新的方法edgeExist2,edgeExist3然后调用它们并省略返回的结果。 – mrok 2012-07-11 23:34:42

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

这应该解开这个谜;)

相关问题