Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does cloning a prototype object provide performance improvement over creating objects from scratch?

Tags:

object

clone

php

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. ;)

like image 743
Ville Mattila Avatar asked Jul 13 '13 12:07

Ville Mattila


1 Answers

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.

like image 160
Sam Burns Avatar answered Oct 06 '22 00:10

Sam Burns