Cześć, trafiłem dzisiaj na dość dziwne zachowanie podczas obliczania dużej ilości wierszy.
Metoda 1:
public function calcReputation ($id) {
$amount = 0;
$posts = DB::instance()->table("posts")->where("user_id", "=", $id)->numRow() > 0 ? DB::instance()->table("posts")->where("user_id", "=", $id)->get(["id"])->results() : null;
if ($posts !== null) {
foreach ($posts as $post) {
$votes = DB::instance()->table("votes")->where("post_id", "=", $post->id)->numRow() > 0 ? DB::instance()->table("votes")->where("post_id", "=", $post->id)->get(["type"])->results() : null;
if ($votes !== null) {
foreach ($votes as $vote) {
if ($vote->type == 1) {
$amount++;
} else {
$amount--;
}
}
}
}
}
return $amount;
}
Metoda 2:
public function calcReputation ($id) {
$amount = 0;
$posts = DB::instance()->table("posts")->where("user_id", "=", $id)->numRow() > 0 ? DB::instance()->table("posts")->where("user_id", "=", $id)->get(["id"])->results() : null;
if ($posts !== null) {
foreach ($posts as $post) {
$votesPositive = DB::instance()->table("votes")->where("post_id", "=", $post->id)->and("type", "=", 1)->numRow();
$votesNegative = DB::instance()->table("votes")->where("post_id", "=", $post->id)->and("type", "=", 0)->numRow();
$amount = $amount + ($votesPositive - $votesNegative);
}
}
return $amount;
}
Z moich oględzin wynika, że czas wyliczenia około 80,000 wierszy metodą pierwszą jest o około 1 sekundę szybszy niż metodą 2. Czy ktoś może mi to jakoś logicznie wytłumaczyć?