Deleting objects in blender can be extremely slow depending on how you do it.
I was writing a python script with over 10,000 objects and had to wait multiple minutes for blender to delete everything until I updated my code.
Originally, I was iterating over every object I wanted to delete, then calling unlink and delete on this object. A significantly faster way to do this is to just unlink every object. Even faster if you can just do it by an entire collection.
Bad Code (bottleneck):
def delete_cubeboard():
# Flush any preexisting objects from collection
# Extreme bottleneck
start = time.time()
for obj in bpy.data.collections.get('animatedcubes').objects:
bpy.data.objects.remove(obj, do_unlink=True)
end = time.time()
print(f'Execute fn> delete_cubeboard: {end-start}s', flush=True)
Good Code (faster)
def delete_cubeboard():
start = time.time()
scene = bpy.data.scenes['Scene']
collection = bpy.data.collections['animatedcubes']
scene.collection.children.unlink(collection)
bpy.data.collections.remove(collection)
targetcollection = bpy.data.collections.new("animatedcubes")
bpy.context.scene.collection.children.link(targetcollection)
# this deletes orphaned data
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
end = time.time()
print(f'Execute fn> delete_cubeboard: {end-start}s', flush=True)
Time reduction:
390s -> 0.96s
Once you're sure it's been unlinked from every scene, it becomes orphaned data. Orphaned data automatically gets deleted by blender on exit. You can clear it manually with the function bpy.ops.outliner.orphans_purge
If you're not using python, you should also be able to apply this method in the GUI (outliner) as well. Unlink the objects you want to delete in the outliner, then purge orphan data (go to the orphan data section on your outliner, and press the button 'purge')