Does cloning a prototype object perform better than comparing objects from scratch?

Below you can see two simplified fragments that do not change in their result.

Sample 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); } 

Sample 2, a clone of the 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 cloning objects (template 2) provide performance improvements when creating objects from scratch (template 1) in terms of memory usage, garbage collection and / or processor cycles? Consider also a large number of fixed properties (which do not change between instances) and a large number of cycles.


Update: I need different instances of objects in each loop. I added the saveToDatabase call to examples similar to this, let him, for example, provide an identifier for this message.;)

+6
source share
2 answers

In your case, cloning objects is not required.

Look at this:

 $message = new Message(); $message->setBody("This is the body of the message."); foreach ($recipients as $recipient) { $message->setRecipient($recipient); $transport->sendMessage($message); } 

This should use the least memory. And you cannot destroy the object. Let GC do it for you.

I'm not sure if you need to manually cancel the installation.

Best way to destroy a PHP object?

What is better for freeing memory with PHP: unset () or $ var = null

In terms of memory usage, cloning should be the same as a new object, as each property is copied. But cloning is a little faster. Check out this test.

0
source

It looks like someone helped you with your code, but in the interests of others who are visiting this question, here is the answer to what is asked in the title:

Usually. The new keyword calls the __construct() magic method; The clone keyword invokes the magic __clone() method.

The Prototype template point should avoid re-launching the expensive constructor, especially when the end result (in terms of the internal state of the objects) is the same every time.

The Prototype pattern is usually used when there is a significant performance issue that needs to be resolved, and not just if you need a lot of objects.

+3
source

Source: https://habr.com/ru/post/949366/


All Articles