Skip to content

Optimize the destructor of WeakMap for large WeakMaps #7672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

TysonAndre
Copy link
Contributor

@TysonAndre TysonAndre commented Nov 20, 2021

Postpone calling any destructors of entries within the weak map
itself until after the singleton EG(weakmap) is updated to remove all
keys in the weak map.

Before, zend_weakref_unregister would do two hash table lookups when freeing an
entry from a WeakMap

  • Free from EG(weakrefs) if that was the last reference
  • zend_weakref_unref_single to remove the entry from the WeakMap itself

After 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 in zend_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.

  • It's possibly worsened when running 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.
                                     |--35.87%--i_free_compiled_variables
                                     |          i_zval_ptr_dtor
                                     |          rc_dtor_func
                                     |          |          
                                     |          |--33.89%--zend_objects_store_del
                                     |          |          |          
                                     |          |           --33.87%--zend_weakmap_free_obj
                                     |          |                     |          
                                     |          |                      --33.39%--zend_weakref_unregister
                                     |          |                                |          
                                     |          |                                |--15.09%--zend_weakref_unref_single
                                     |          |                                |          |          
                                     |          |                                |           --15.02%--zend_hash_index_del
                                     |          |                                |                     |          
                                     |          |                                |                      --0.52%--_zend_hash_del_el_ex
                                     |          |                                |          
                                     |          |                                |--13.49%--zend_hash_index_find_ptr
                                     |          |                                |          |          
                                     |          |                                |           --13.41%--zend_hash_index_find
                                     |          |                                |                     |          
                                     |          |                                |                      --13.28%--zend_hash_index_find_bucket
                                     |          |                                |          
                                     |          |                                 --4.04%--zend_hash_index_del
                                     |          |          
                                     |           --1.96%--zend_array_destroy
                                     |                     |          
                                     |                      --1.88%--i_zval_ptr_dtor
                                     |                                |          
                                     |                                 --1.40%--rc_dtor_func
                                     |                                           |          
                                     |                                            --1.19%--zend_objects_store_del
<?php

class Example {
}

function bench_weak_map(int $n) {
    $wm = new WeakMap();
    $values = [];
    for ($i = 0; $i < $n; $i++) {
        $x = new Example();
        $wm[$x] = true;
        $values[] = $x;
    }
    return [$values, $wm];
}

/*
function bench_spl_object_storage(int $n) {
    $wm = new SplObjectStorage();
    $values = [];
    for ($i = 0; $i < $n; $i++) {
        $x = new Example();
        $wm[$x] = true;
        $values[] = $x;
    }
    return [$values, $wm];
}

function bench_dynamic_property(int $n) {
    $values = [];
    for ($i = 0; $i < $n; $i++) {
        $x = new Example();
        $x->dynamic2 = 123;
        $values[] = $x;
    }
    return $values;
}


function main(int $n) {
    error_reporting(E_ALL & ~E_DEPRECATED);
    foreach (['bench_weak_map', 'bench_spl_object_storage', 'bench_dynamic_property'] as $f) {
        gc_collect_cycles();
        $t1 = hrtime(true);
        $m1 = memory_get_usage();
        $v = $f($n);
        $t2 = hrtime(true);
        $m2 = memory_get_usage();
        unset($v);
        $t3 = hrtime(true);
        printf("%25s: %d bytes create=%.6f total=%.6f\n", $f, $m2 - $m1, ($t2 - $t1)/1e9, ($t3 - $t1)/1e9);
    }
    echo "\n";
}
*/

while(true) {
    bench_weak_map(1000000);
}

=====================================================================
FAILED TEST SUMMARY
---------------------------------------------------------------------
FPM: Process manager config pm.process_idle_timeout [sapi/fpm/tests/proc-idle-timeout.phpt]
=====================================================================

Build failures are unrelated

Postpone calling any destructors of entries within the weak map
itself until after the singleton `EG(weakmap)` is updated to remove all
keys in the weak map.

Before, zend_weakref_unregister would do two hash table lookups when freeing an
entry from a WeakMap

- Free from `EG(weakrefs)` if that was the last reference
- zend_weakref_unref_single to remove the entry from the WeakMap itself

After this change, only the first hash table lookup is done.
The freeing of entries from the weak map itself is done sequentially in
`zend_hash_destroy` without hashing or scanning buckets.

It may be a good idea to prevent modification of a WeakMap after the weak map
starts to get freed.
@TysonAndre TysonAndre requested a review from nikic November 21, 2021 15:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants