Optimize the destructor of WeakMap for large WeakMaps #7672
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Postpone calling any destructors of entries within the weak map
itself until after the singleton
EG(weakmap)
is updated to remove allkeys in the weak map.
Before, zend_weakref_unregister would do two hash table lookups when freeing an
entry from a WeakMap
EG(weakrefs)
if that was the last referenceAfter this change, only the first hash table lookup in
EG(weakrefs)
is done.The freeing of entries from the weak map itself is done (with this PR) sequentially in
zend_hash_destroy
without hashing or scanning buckets.In the future, It may be a good idea to prevent modification of a WeakMap after the weak map
starts to get freed, since there may be obscure edge cases before and after this PR.
(e.g. for cyclic data structures
$a->map = new WeakMap(); $a->map[$a] = $a;
the destructor of$a
may modify the map)perf
shows a lot of time is spent inzend_weakref_unref_single
for synthetic benchmarks.(Aside: The choice of
index = ptr | tag_2bit
may have a lot of hash collisions in the worst case due to the least significant bits being the same, causing hash collisions. Changing it to use bit shifts and the most significant bits for tags instead (on platforms where it was possible) didn't seem to help too much)Attempting to benchmark the below script https://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html#C shows half of the time freeing the WeakMap is spent on a hash table lookup of the entry already selected in the weak map itself.
main
instead due to hash table collisions, with the allocated objects tending to share least significant bits due to the order they were created in.Build failures are unrelated