Created
July 22, 2014 19:30
-
-
Save michelbrito/409f7c02196ecd1ed4ea to your computer and use it in GitHub Desktop.
Magento count() vs getSize()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
O COUNT() primeiro carrega toda a collection e depois conta quantos itens tem. Por isso dependendo da situação, não é melhor opção a se usar para saber se tem registros. | |
Arquivo: lib/Varien/Data/Collection.php | |
public function count() | |
{ | |
$this->load(); | |
return count($this->_items); | |
} | |
*/ | |
$collection = Mage::getResourceModel('catalog/product_collection') | |
->addAttributeToSelect('*') | |
->addAttributeToFilter('price', array('lt' => 10)); | |
echo $collection->count(); | |
echo "<br />"; | |
/* | |
O GETSIZE() executa uma consulta ao banco, que retorna apenas a quantidade total de registros, sem precisar carregar toda a collection para depois contar quantos registros tem. Por isso é muito mais rapido. | |
Arquivo: lib/Varien/Data/Collection/Db.php | |
public function getSize() | |
{ | |
if (is_null($this->_totalRecords)) { | |
$sql = $this->getSelectCountSql(); | |
$this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams); | |
} | |
return intval($this->_totalRecords); | |
} | |
*/ | |
$collection = Mage::getResourceModel('catalog/product_collection') | |
->addAttributeToSelect('*') | |
->addAttributeToFilter('price', array('lt' => 10)); | |
echo $collection->getSize(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment