Collection count() vs getSize()
TLDR;
For a collection with 197467 items:
count()
= 4.0s
getSize()
= 0.0010s
There are lots of times when, to perform some business logic, you need to know how many items are in a collection. Sometimes you need to know if there are any items in the collection at all and other times you need to know the exact number of items.
Traditionally in Magento you will be working with a Collection
object. A collection object extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
.
This class has two methods for getting the number of items in the collection: count()
and getSize()
. Let's take a look at the difference between these two methods.
count()
public function count()
{
$this->load();
return count($this->_items);
}
count
calls load()
which will load the entire collection and then uses the PHP count()
function to get the number of items in the collection. On a large collection this can be pretty expensive.
getSize()
if ($this->_totalRecords === null) {
$sql = $this->getSelectCountSql();
$this->_totalRecords = $this->_totalRecords ?? $this->getConnection()->fetchOne($sql, $this->_bindParams);
}
return (int)$this->_totalRecords;
getSize()
checks for the _totalRecords
property. If it is not set then it will craft a SQL query to get the number of items in the collection. This is can be more efficient than loading the entire collection and then counting the items. There IS still a performance hit here though as it is still making a database query.
Summary
If you have already loaded the collection then it won't make much difference which method you use. If you haven't loaded the collection then getSize()
will be much more efficient.