ARTICLEwiki.php.net4 min read

Optimizing Closures in PHP 8.6

Optimizing Closures in PHP 8.6

AI Summary

In PHP 8.6, I propose two key optimizations for closures, including arrow functions, which may introduce some backward compatibility (BC) breaks but promise significant performance gains. The first optimization involves converting non-static closures into static ones when they don't utilize $this, eliminating unnecessary reference cycles that previously required PHP's cycle collector to resolve. This change reduces memory usage and enhances performance by avoiding cycles that don't need to exist.

The second optimization focuses on caching stateless closures—those that are static and don't capture or declare variables—between uses. This prevents the creation of redundant closure instances, as demonstrated by a benchmark that showed an 80% performance improvement in a synthetic test. In practical applications like Laravel, this optimization reduced closure instantiations by 65%, leading to a 3% performance boost.

While these changes introduce some BC considerations, such as ReflectionFunction::getClosureThis() returning NULL for inferred static closures, these are generally predictable and align with expected behaviors. Additionally, two stateless closures from the same lexical location will now be identical, which is a shift from previous behavior.

To maintain backward compatibility, Closure::bind() and Closure::bindTo() will allow binding objects to inferred static closures, discarding them only when explicitly static. This ensures that closures inferred as static due to unrelated changes remain compatible.

The community vote on these optimizations was overwhelmingly positive, with 24 votes in favor and none against, indicating strong support for these enhancements in PHP 8.6.

Key Concepts

Closure Optimization

Closure optimization involves improving the efficiency and performance of closures, which are functions that can capture variables from their surrounding scope.

Static Closure Inference

Static closure inference is the process of determining when a closure can be treated as static, meaning it doesn't rely on the instance of the class in which it was created.

Stateless Closure Caching

Stateless closure caching involves storing closures that don't capture or declare variables, allowing them to be reused without creating new instances.

Category

Programming
M

Summarized by Mente

Save any article, video, or tweet. AI summarizes it, finds connections, and creates your to-do list.

Start free, no credit card