search
HomeBackend DevelopmentPHP TutorialPHP: The Garbage Collector explained with simple words

The Garbage Collector (GC) is the internal memory management system in PHP, but there are some subtleties to understand.

? Why does the GC even exist?

The GC automates memory management, which removes the hassle of handling memory with manual tasks (which would be tedious).

This allows developers to focus on their business logic without worrying excessively about 'Out of Memory' errors.

Of course, it's not magic.

? 10,000 objects in short

Freeing objects that are no longer needed prevents memory leaks.

The GC uses a counting mechanism to determine the elements to drop. If no references point to a particular object (i.e., $counter = 0), then this object is eligible for cleanup.

It works pretty well, but some references can be problematic:

class A {
    public $b;
}

class B {
    public $a;
}

$a = new A();
$b = new B();

$a->b = $b;
$b->a = $a;

unset($a);
unset($b);

In this case of poor design, PHP will not free the memory even if we unset $a and $b, as they reference each other, leading PHP to believe they are still in use.

Fortunately, there is another mechanism called the Cycle Collector for that:

gc_collect_cycles();

Roughly speaking, the collector traverses all references and applies an algorithm to mark objects in use, which reveals objects to collect (the unmarked ones).

However, PHP does not trigger automatic cycle collection until the thresholds of 10,000 objects with potential cyclic references is reached.

Again, it's not magic, so you must invoke gc_collect_cycles() only in few cases.

? TANSTAAFL

Bad design can lead to overcomplex relationships between objects, leading to more references and more frequent garbage collection.

Each reference-counted object requires additional storage for its reference count.

Source: Wikipedia - Reference counting

The overhead associated with memory cleanup operations can impact the global performance significantly and ultimately increase the execution time in specific scenarios.

10 years ago, Composer got a huge performance boost just by using the gc_disable() function.

Source: Composer - disabling GC

Indeed, PHP 7 drastically improved the GC, so it is not what it was in 2014.

In addition, PHP 8 versions improved memory allocation strategies and added more useful statistics about GC operations for better monitoring (gc_status() in 8.3).

Most PHP applications are request-driven, and the memory is automatically cleared at the end of the request.

Again, it's pretty cool but not magic. What happens with asynchronous requests and long-lived objects/daemons?

You may experience memory leaks at some point.

? How different is the PHP's GC?

At this point, you might not see how the PHP's GC differ from other languages.

Most of the time, other languages do not rely on reference counting to collect garbage or may use different implementations.

For example, many use the tracing algorithm that also marks unused objects but does not operate incrementally. It's a graph traversal.

Besides, some languages do not allow such direct control (e.g., on/off at runtime).

As usual, there are some advantages and inconvenients, so you may see some hybrid approaches.

?‍? Interacting with the PHP's GC

You can leverage the built-in gc_* helpers.

For example:

  • gc_collect_cycles manually triggers the garbage collection
  • gc_status() give the current status
  • gc_disable() disables it
  • gc_enable() enables it

These functions are helpful for debugging or fine-tuning garbage collection when necessary.

? Understanding memory errors

You can read this post for further insights:

PHP: The Garbage Collector explained with simple words

PHP: memory errors

spO0q ? ・ May 24 '23

#php #beginners #programming

? Weak Maps to the rescue?

PHP 7.4 introduced Weak References and PHP 8 introduced Weak Maps.

A Weak Map could be described as a collection of Weak References.

This data structure is a versatile key-value store that helps PHP keep track of items without creating clutter or consuming excessive space.

You may see it as a temporary storage that will be cleared right away when it's no longer needed, as there are no [strong] reference that could prevent the garbage collection:

class A {
    public $b;
}

class B {
    public $a;
}

$a = new A();
$b = new B();

$a->b = $b;
$b->a = $a;

unset($a);
unset($b);

✅ Pros

  • pretty straightforward
  • great for caching or memoization (e.g., expensive computations)

❌ Cons

  • while keys (objects) do not prevent garbage collection, values can, so the term "arbitrary values" can be misleading (only use simple data types as values)
  • valuable use cases are limited

? Optimize the code

  • leverage design patterns that reduce interdepencies
  • use dependency injection
  • don't load too large datasets into memory and use collections and generators instead of huge arrays
  • monitor memory usage
  • profile your code with metrics
  • use gc_enable(), gc_disable(), and gc_collect_cycles() sparingly

Wrap up

For most usages, you won't have to worry about memory management, as PHP already handles it.

However, because modern stacks utilize long-lived objects, you need to monitor your application for potential memory leaks.

If you get issues, you may have to optimize the code and/or interact with the GC directly.

The above is the detailed content of PHP: The Garbage Collector explained with simple words. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software