Minor optimization for set object, swap bodies #142659
Copy link
Copy link
Open
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement
Description
Based on this observation:
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.
Linked PRs
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement
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