Is it faster to compare strings or instances?

In my script, I’m getting all of the parts within a radius, then iterating over them to do something specific to my game that’s not really relevant here. For each part, I make sure it’s a part I want to manipulate by using if part.Parent ~= ground then continue end. Each of the relevant parts share the same name and parent.

This means I have a decision to make: do I compare the parent of the part with the ground instance, or do I compare the name of the part to the name I expect each of the relevant parts to have? The main consideration here is performance, another is code readability and maintainability.

I believe that it’s faster to compare strings than to compare instances, but I’m not sure, so I could use some help here.

EDIT: Changed the condition to something more appropriate for a loop (i forgor)

The difference is negligible if you ask me. Comparing strings would definitely be faster though

OK, thanks. Performance is really important here because of the massive amount of parts being gone through, especially considering that all of this will be running on the client.

At this point, the comparison is pretty much negligible and appears more like a micro-optimization. Usually comparing primitives are faster than the complicated data structures, but the difference is slim to not be noticeable in one exact execution.

You can remove the unnecessary parts from the list

It takes about 0.03118239999457728 seconds to compare the same strings 5 million times, and takes about 0.09074449999025092 seconds to compare the same Instance game also 5 million times. So yeah, comparing strings would be much faster. But…

When you try to compare the property of an Instance, let’s say game.Name, to the same property over 5 million times, it takes about 1.914308199993684 seconds. In my case, I can just store the property in a local variable so that it would save the value in memory and it would be optimized to the point that it takes 0.04905269999289885 seconds to compare. However, for your case, you are indexing into the .Parent property, getting the parent Instance then comparing it with the ground instance, which would take longer than getting a more simpler property such as the .Name string.

The approach you described below may be the best solution.

Regardless of which is fastest, I’d recommend sticking with checking the part’s parent. Checking the part’s name could lead to issues if you either forget to name it, or have a typo. IMO the robustness of your code should be more important than performance

If you’re extremely careful about naming them, or are doing so automatically using a script, then checking their names is a bit faster (tested 1.0139710000003106 vs 1.278934100000697 for 9,999,999 iterations)

1 Like