They basically produce the same sql. Count(*) is a bit slower than count(active) or specifying a field, just like select a, b, c is faster than select *.
->count() VS select count(*) As count
CaseA:
$count = App\Flight::where('active', 1)->count();
CaseB:
$collections = App\Flight::selectRaw('COUNT(*) AS count')->where('active', 1)->first();
$count = $collections->count;
CaseB should be faster than CaseA ?
hmmm just for example, i know the column name, COUNT(id) count
and there is 5,000,000 rows in the collections
so is database return a count number VS use count(the array has 5,000,000 rows)
what the method ->count() used in Laravel , just use count(array()) ?
No, it's selecting the count in the query just as you are in your 2nd one. There's lots of shortcuts in eloquent. Like ->latest() produces "ORDER BY created_at DESC".
Install a tool like laravel debugbar, so you can see all of the actual queries being run. It's quite useful. https://github.com/barryvdh/laravel-debugbar
i have installed laravel-debugbar, tested on 350,000 rows data
CaseB is faster than CaseA
i think because in CaseA need to use php count(if many elements means need more time)
Then what are the queries both produce? You're 2nd one uses ->first(), which adds "LIMIT 1".
http://os33.atwebpages.com/laravel_debugbar.html
i captured the screen, the 1st query is CaseA, and 2nd is CaseB
oops, ->count() means use Count(*) in the query or use php count(result set) ?
It shows using count in the query, so it's not using php's count(result set). And yes, limit 1 will slightly make it faster as you're explicitly limiting the result set.
so means if i use CaseB is better than use CaseA ?
because i tested on a table has 350,000 rows data only
on another table has 3,200,000 rows, so i want to write a model, but donno which case is more better
It's up to you. There was only a 15ms difference in time, which is pretty trivial. So, it might take ~137ms, which is still pretty trivial. It's not even .25 seconds.
The difference seems negligible. I'd use the one that is easiest to work with. (Case A)
ok thankyou @Cronix and @BrandonSurowiec
Please or to participate in this conversation.