1

Which of the following is correct and what is the difference between these?

foreach($productIds as $id)
{
    $product = $this->_productFactory->create()->load($id);
    $product->save();
}

or

$productFactory = $this->_productFactory->create();
foreach($productIds as $id)
{
    $product = $productFactory->load($id);
    $product->save();
}
2

Try first code which is


foreach($productIds as $id) {
    $product = $this->_productFactory->create()->load($id);
    $product->save();
}

This code create every product instance that is exactly factory do.

Also avoid load/save using model class. All are deprecated. Use repository.

  • This will create an object for each iteration, correct? But this will not create object for each iteration. $productFactory = $this->_productFactory->create(); foreach($productIds as $id) { $product = $productFactory->load($id); $product->save(); } – Octopus Jul 3 '18 at 11:03
1

Functionally, there is no difference. Both snippets do the same thing.

There may be a minor performance improvement by calling the create() method outside of the loop, but it is unlikely to be large enough to for me to say definitively "you should do it this way for performance reasons".

The real performance impact comes from loading and saving products inside a loop. This is a big no-no.

A better approach is to pass the $productIds as a parameter to the get method of the Product repository. That'll give you back an array of loaded products, which you can then iterate over in the same way as your snippets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.