PHP Garbage Collector and Magento

Developers Showcase: Garbage Collector

Memory management is a concern of many software developers, but it's not an obstacle Magento developers are burdened with. Magento developers Andrey Tserkus and Vladimir Pelipenko shared their perspective.


Andrey, what's so exciting about memory management in PHP?

"What's most exciting about it is actually the fact that there is none. If you've worked with other programming languages, then you know what a nightmare it is to track every new object you've created and new memory block allocated. As PHP-developers, we can use variables whenever we want to, we can drop objects at any point, and there is no limit on the number of arrays we can clone and create. We are fortunate to have an underlying language layer that takes care of memory management on its own. With PHP, you can stop worrying and begin programming!"

"There are some cases, though, when PHP developers should be concerned with memory script. If a script generates a large amount of reports, calls out to a lot of images, or transfers a large amount of data then it’s likely the script will exhaust all of its allocated memory - thus creating a fatal error. That's why PHP has a special resource manager to deal with it - the Garbage Collector."

image

Well, Vladimir, what is a Garbage Collector?

"The Garbage Collector is a tool that travels through allocated memory, checks the resources in use and returns unused resources back to the memory pool. It's not something developers control; it's invoked automatically when PHP finds that available resources are nearly depleted."

How does the Garbage Collector know that a variable or object is still in use?

"Each memory block in PHP has an internal counter called refcount. Whenever a variable links to that block, its refcount is incremented. When the link is broken, refcount is decremented. Memory blocks with a refcount equal to zero are not in use and may be safely returned to the memory pool."

When Magento developers are working on long-running tasks what should they do?

"When working on tasks with a long duration time, one should follow several coding practices. For example, to avoid memory leaks when processing a large amount of products, call the product’s clearInstance() method, once you've finished handling it. If you've made a custom module that sets objects inside products, clean these objects by overriding the product's core methods or observing events. In general, memory leaks are possible in any object or array. whenever you process a lot of data think about circular references and help the Garbage Collector by breaking them."


image

To further explore PHP memory management, and its impact on Magento, view the full article:


RSS: This Entry| All Blog Posts (RSS)