2010-12-22 35 views
1

哪两个会更快,如何能做到这样的测量这两个会更快

foreach ($posts as $post) 
{ 
$totalikes = count($post["Like"]); 
$totacomments = count($post["Comment"]); 
$max = ($totalikes < $totacomments)? $totacomments : $totalikes; 
for($i=0;$i<$max;$i++) 
{ 
    if(isset($post["Like"][$i])) 
    $users[] = $post["Like"][$i]["user_id"]; 
    if(isset($post["Comment"][$i])) 
    $users[] = $post["Comment"][$i]["user_id"]; 
} 
} 

foreach ($posts as $post) 
{ 
foreach ($post["Like"] as $like) 
{ 
    $users[] = $like["user_id"]; 
} 
foreach ($post["Comment"] as $comment) 
{ 
    $users[] = $comment["user_id"]; 
} 
} 

其中两个是更好

+0

为了清晰起见,我会选择第二个。性能差异可能可以忽略不计... – 2010-12-22 09:57:05

回答

1

第二方法。

第一种方法是将开销如果$post['like'] & $post['comment']计数不同

PS:第一种方法不会做同样的事情,第二个方法呢?

方法A

总环路= 2 x max array size
方法B总环路= size of array A+size of array B

至于$users,应该是两个方法相同

+0

为什么错误/差异 – aWebDeveloper 2010-12-22 09:34:54