You can see two simplified snippets below that don't vary in their outcome.
Pattern 1, objects from scratch:
foreach ($recipients as $recipient) {
$message = new Message();
$message->setBody("This is the body of the message.");
$message->setRecipient($recipient);
$transport->sendMessage($message);
$persister->saveToDatabase($message); // Updated line
unset($message);
}
Pattern 2, cloning a prototype object:
$prototype = new Message();
$prototype->setBody("This is the body of the message.");
foreach ($recipients as $recipient) {
$message = clone $prototype;
$message->setRecipient($recipient);
$transport->sendMessage($message);
$persister->saveToDatabase($message); // Updated line
unset($message);
}
unset($prototype);
Does the object cloning (pattern 2) provide performance improvements over creating objects from scratch (pattern 1) in terms of memory usage, garbage collection and/or CPU cycles? Consider also high number of fixed properties (that do not change between the instances) and high number of loops.
Update: I need different object instances in each loop. I added saveToDatabase
call to the examples to resemble that, let it for example give an ID to the message. ;)