Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Magento 2 snippet to compare performance of product collections with and without call of ->getCustomAttributes()
<?php
namespace IntegerNet\CustomAttributeTest\Console\Command;
use Magento\Catalog\Model\Product;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
class ProductCollectionCommand extends \Symfony\Component\Console\Command\Command
{
/**
* @var ProductCollectionFactory
*/
private $productCollectionFactory;
public function __construct(
ProductCollectionFactory $productCollectionFactory
) {
parent::__construct();
$this->productCollectionFactory = $productCollectionFactory;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('productcollection:test')
->setDescription('Test performance of product collections with and without using ->getCustomAttributes()')
->setDefinition([]);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$description = 'Without call of $product->getCustomAttributes()';
$this->traverseCollection($productCollection, $description, $output, false);
$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$description = 'With call of $product->getCustomAttributes()';
$this->traverseCollection($productCollection, $description, $output, true);
}
private function traverseCollection(
ProductCollection $productCollection,
string $description,
OutputInterface $output,
bool $callCustomAttributes = false
) {
$count = 0;
$startTime = microtime(true);
foreach ($productCollection as $product) { /** @var Product $product */
$count++;
if ($callCustomAttributes) {
$product->getCustomAttributes();
} else {
$product->getData();
}
}
$elapsedTime = number_format(microtime(true) - $startTime, 2);
$output->writeln('');
$output->writeln('<info>' . $description . ':</info>');
$output->writeln('<info>' . $count . ' products traversed in ' . $elapsedTime . 's</info>');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.