48

PHP: rfc:weak_maps

 4 years ago
source link: https://wiki.php.net/rfc/weak_maps
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Weak maps allow creating a map from objects to arbitrary values (similar to SplObjectStorage) without preventing the objects that are used as keys from being garbage collected. If an object key is garbage collected, it will simply be removed from the map.

In PHP 7.4 first-class support for weak references was already introduced. However, raw weak references are only of limited usefulness by themselves and weak maps are much more commonly used in practice. It is not possible to implement an efficient weak map on top of PHP weak references, because the ability to register a destruction callback is not provided.

The general use case for weak maps is to associate data with individual object instances, without forcing them to stay alive and thus effectively leak memory in long-running processes. For example, a weak map may be used to memoize a computation result:

class FooBar {
    private WeakMap $cache;
 
    public function getSomethingWithCaching(object $obj) {
        return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);
    }
 
    // ...
}

This will invoke the computeSomethingExpensive() method only once for each object. At the same time it will also drop the cached value from the map if the object is destroyed. Doing the same with a normal array (or rather SplObjectStorage) would result in a memory leak.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK