You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Minor optimization for set object, swap bodies #142659
set_swap_bodies is only called in two locations in this file. For both cases the second argument b is a newly created temporary which is discarded afterwards. So we could replace part (all?) of these branches with asserts. Part of the other work (e.g. copying back to b) might not be needed for the same reason.
We should investigate this idea and see if it's worth it.
I spent time trying to implement this optimization and found no easy fix. I realized that in order to optimize set_swap_bodies, you would basically need to manually free memory. For example, you would need to individually free each key in the set a in order for the set object to still exit in memory but not any of its keys (which we want to replace with the keys of set b).
However there are two small optimizations you could do:
As @eendebakpt mentioned, you can add an assert and get rid of if statements (especially the ones that are never true)
Since tmp is uniquely referenced in set_intersection_update and set_intersection_update_multi, do you need atomic operations on b in set_swap_bodies? This could possible speed up the free-threaded build.
I am not sure if these changes are worth a PR though.
Activity
brijkapadia commentedon Mar 9, 2026
For reference, the two functions that call
set_swap_bodiesareset_intersection_updateandset_intersection_update_multi_impl:set_intersection_update
cpython/Objects/setobject.c
Lines 1792 to 1803 in 63eaaf9
set_intersection_update_multi_impl
cpython/Objects/setobject.c
Lines 1813 to 1828 in 63eaaf9
I spent time trying to implement this optimization and found no easy fix. I realized that in order to optimize
set_swap_bodies, you would basically need to manually free memory. For example, you would need to individually free each key in the setain order for the set object to still exit in memory but not any of its keys (which we want to replace with the keys of setb).However there are two small optimizations you could do:
assertand get rid of if statements (especially the ones that are never true)tmpis uniquely referenced inset_intersection_updateandset_intersection_update_multi, do you need atomic operations onbinset_swap_bodies? This could possible speed up the free-threaded build.I am not sure if these changes are worth a PR though.
Happy to dig deeper if you think it is worth it.
pythongh-142659: Optimize set_swap_bodies for intersection_update
Add news entry for pythongh-142659
pythongh-142659: Optimize set_swap_bodies for intersection_update
Add news entry for pythongh-142659
pythongh-142659: Move GIL/free-threading branch into copy_small_table
pythongh-142659: Use PySet_Check in set_replace_body assertions