Generating Objects: Skript gets slower

Hello all,

I’m facing a problem while creating objects with the python api using blender 3.0.0. The more objects get created the slower the creation gets even though old objects are deleted.
I created a test script to create 50 cubes at a time, delete them and create another 50 cubes. After 200 iterations the time needed to create 50 cubes is 3 times higher. To create the first 50 cubes blender only needs 1.9 ms. The last 50 cubes need 6.4 ms to create. Why is that? If I start the script again without reopening the time is low again.

import bpy
import datetime

def main():
    master_cube = bpy.data.objects['Cube']
    for i in range(1,200):
        for collection in bpy.data.collections:
            if collection.name == "Collection":
                for obj in collection.objects:
                    bpy.data.objects.remove(obj, do_unlink=True)
                break
        for block in bpy.data.meshes:
            if block.users == 0:
                bpy.data.meshes.remove(block)
        time_stamp = datetime.datetime.now()
        for j in range(0,50):
            new_cube = master_cube.copy()
            new_cube.data = master_cube.data.copy()
            bpy.data.collections['Collection'].objects.link(new_cube)
        milliseconds = (datetime.datetime.now()-time_stamp).total_seconds()*1000
        print('Data Generation Time: ' + str(milliseconds) + ' ms')
main()

Thanks a lot for your help.

test.blend (4.7 MB)

Edit: added the blend file for testing

It has been mentioned dozens of times, that creating many objects is very slow, but nothing has been done so far. It is because when an object is created, Blender will have to loop all other objects so that it makes sure that it has a unique name and such (same goes for object-blocks then for mesh-blocks etc).

Though I have not check 100% the code on github to show you, this is the general idea. But if someone knows exactly to explain is free to do so.

As for example if there is an object ‘Cube’ in the scene, you try to name something else ‘Cube’ then your naming will be set to ‘Cube.001’ automatically, this is the mechanism that ensures unique names in action.

This translates to lots of iterations behind the scenes. As for example having 200 objects. You would get 200 for all objects and 200 for all meshes.