If need update product attribute at existing product normal way it will take much time to save. Example of usual code(take lot of time for saving):
protected $_productRepository; .... public function __construct( .... \Magento\Catalog\Api\ProductRepositoryInterface $productRepository .... ){ $this->_productRepository = $productRepository; } .... $product = $this->_productRepository->get($sku); $product->setData('some_attribute', 'some value'); $this->_productRepository->save($product);
Example code for speed up product update attribute:
protected $_productRepository; protected $_productResource; .... public function __construct( .... \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\Catalog\Model\ResourceModel\Product $productResource .... ){ $this->_productRepository = $productRepository; $this->_productRepository = $productRepository; } .... $product = $this->_productRepository->get($sku); $product->setData('some_attribute', 'some value'); $this->_productResource->saveAttribute($product, 'some_attribute');
Script for testing speed:
<?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $product_id = 4; $product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id); $start = microtime(true); $productResource = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product'); $product->setName('new product name 1'); $productResource->saveAttribute($product, 'name'); echo "Save attribute duration: ".(microtime(true) - $start)." seconds\n"; $starttime = microtime(true); $product->setName('new product name 2'); $product->save(); echo "Save product duration: ".(microtime(true) - $start)." seconds\n";
Resource – https://mage2-blog.com/magento-2-speed-up-product-save/