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. ;)
Looks like someone has helped you with your code, but for the benefit of others visiting the question, here's the answer to what is asked in the title:
Usually. The new
keyword causes the __construct()
magic method to run; the clone
keyword causes the __clone()
magic method to run.
The point of the Prototype Pattern is to avoid rerunning an expensive constructor repeatedly, especially when the end result (in terms of the internal state of the objects) is the same each time.
The Prototype Pattern is only normally used where there is a significant performance problem that needs to be addressed, not just if you need a lot of objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With