Hi folks, I'm wondering between Query vs Foreach loop, Which one has the better performance?
Here is a simple example, my web app, has a reply table and like table, the reply and like has onetomany relationship, a reply can have many likes and a like belong to a reply
and in this function I need to get a like record/model that is liked by current auth user
1, Using query
public function likeReply(Request $request)
{
$reply = Reply::find($request->id);
$likeByUser = Like::where([
['user_id', '=', Auth::id()],
['likeable_type', '=', 'App\Reply'],
['likeable_id', '=', $reply->id],
])->first(); //The Query
//other line of code
}
2, Using foreach loop
public function likeReply(Request $request)
{
$reply = Reply::find($request->id);
$likeByUser = null;
foreach($reply->likes as $like)
{
if($like->user_id == Auth::id() &&
$like->likeable_type == 'App\Reply' &&
$like->likeable_id == $replyId)
{
$likeByUser = $like;
break;
}
} //The Foreach loop
//other line of code
}
Both method can get the like record/model that is liked by current auth user (it has the same result)
But I'm wondering which one has a better perfomance (speed, etc), if for eg. in my like table has 10,000 likes record in the DB?
and if you know which one perform better, can you give me a simple explanation why it has better perfomance?
Thanks