Most efficient way to get all ID's from a collection

Actually getAllIds is the best way of doing it. For example in the product collection resource model the method looks like this:

public function getAllIds($limit = null, $offset = null)
{
    $idsSelect = $this->_getClearSelect();
    $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
    $idsSelect->limit($limit, $offset);
    $idsSelect->resetJoinLeft();

    return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
}

So everything is retrieved from a single select and no iteration is required. Also in the abstract resource model it looks like this:

public function getAllIds()
{
    $idsSelect = clone $this->getSelect();
    $idsSelect->reset(Zend_Db_Select::ORDER);
    $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
    $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
    $idsSelect->reset(Zend_Db_Select::COLUMNS);

    $idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
    return $this->getConnection()->fetchCol($idsSelect);
}

So everything that extends Mage_Core_Model_Resource_Db_Collection_Abstract should use this unless specified otherwise.

The method you looked at comes from the base class Varien_Data_Collection but it is overwritten in its children.


In this case you can use the collection object

$collection = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect('entity_id');

[...] 
do your loop
[...]

addAttributeToSelect for entity_id is not really required but for demonstrating purposes I put it in, add the fields you need and you're done!

More on collections you'll find on this Wikipage


More Optimized

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->reset(Zend_Db_Select::COLUMNS);
$collection->getSelect()->columns('entity_id');
$collection1Ids[] = $collection->getAllIds();

Tags:

Collection