SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH

Optimize performance code Magento 2

  1. Loops

Not use count() function inside the condition part of a for statement:

for ($i = 0; $i < count($items); $i++) {
 //some code
}

The code should be:
$itemNum =count($items);
for ($i = 0; $i < $itemNum; $i++) {
 //some code
}

SQL Queries Inside a Loop

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

foreach ($this->getProductIds() as $productId) {
 $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
 echo $product->getName();
}
The code should be:
$collection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
 ->addFieldToFilter('entity_id', array($this->getProductIds()))
 ->addAttributeToSelect('name');
foreach ($collection as $product) {
 echo $product->getName();
}

Loading the same model multiple time

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$name = $objectManager->create('Magento\Catalog\Model\Product')->load($productId)->getName();
$sku  = $objectManager->create('Magento\Catalog\Model\Product')->load($productId)->getSku();
$attr = $objectManager->create('Magento\Catalog\Model\Product')->load($productId)->getData('attribute_name');

The code should be:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product'->load($productId);
$name = $product->getName();
$sku  = $product->getSku();
$attr = $product->getData('attribute_name');

Collections

Collections are often used to retrieve only one item by calling the $collection->getFirstItem() method
or returning the first item on the first iteration of the loop. A common mistake of inexperienced Magento
developers is not applying a limitation on the collection’s query results.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
			 ->addAttributeToSelect('name')
			 ->addAttributeToFilter('DESC');
$product = $collection->getFirstItem();

The code should be:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
			 ->addAttributeToSelect('name')
			 ->addAttributeToFilter('DESC')
                         ->setPageSize(1);

$product = $collection->getFirstItem();