Hey!
I have been working on a build for my project. Unfortunately, I’m a relatively sloppy builder, and I abuse the duplication (Ctrl D) function all the time. As a result, I often end up making many unnecessary duplications that I later have no recollection of, and when I say “many”, I truly mean many. Sometimes, I’ll find that I’ve made up to 4-5 copies of the exact same instance without my knowledge.
This is all fine and dandy in small projects, but it becomes a problem when my builds become more massive—a problem I’ve largely ignored until this point in time. Now, I have a large build with potentially many duplicated clones, and I want to get rid of them.
Solving this problem seemed to be most plausible through scripting. Initially, I wrote the following code and pasted it into the command bar:
local saved = {}
local start = tick()
local items = 0
for index, object in pairs (workspace:GetDescendants()) do
if object:IsA("BasePart") then
for index2, object2 in pairs (saved) do
if object.CFrame == object2.CFrame and object.Size == object2.Size then
object:Destroy()
items = items + 1
continue
end
end
table.insert(saved, object)
end
end
local delta = tick() - start
print("Number of items: ", items)
print("Time elapsed: ", delta)
Essentially, I loop through each instance in the workspace, check if it’s a BasePart, and if it is, loop through a table of saved instances to see if it matches up with any of them in terms of CFrame and size (implying a cloned duplicate). If it does, I delete the object. If it does not, I add it to the saved table. I also added some tracker variables for my own curiosity.
The obvious problem with this is that this is an O(n^2) time complexity algorithm and extremely inefficient for the task at hand. I think I have about 50,000 parts in my workspace, so clearly this solution will not work. As expected, when I tried to run the code, studio stalled and crashed. Also, there is a possibility that my code is wrong, so if you notice anything, let me know.
Do you guys have any recommendations on what I should do? Is there a better search algorithm for my unsorted saved table?