2012-07-11 49 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; 
} 

這應該解開這個謎;)

相關問題