Which is better for optimization?

So I was just making this quick function to turn off CanTouch for all the parts in this group, and I was wondering if anyone knows if it’ll use less processing power to use an if statement (to only change CanTouch for the parts that it can be changed in), or a pcall function (that will just block out the errors from the code trying to change Cantouch for the objects that it can’t be changed in).

This is what it would look like if it had a pcall function

for i,v in ipairs(script.Parent:FindFirstChild("Golden robot"):GetChildren()) do
	local _,_ = pcall(function()
		v.CanTouch = false
	end)
end

This is what it would look like if it had an if statement

for i,v in ipairs(script.Parent:FindFirstChild("Golden robot"):GetChildren()) do
	if v:IsA("Part") then
		v.CanTouch = false
	end
end

If I did not explain it properly, please ask me to rephrase it.

Any help would be appreciated. :+1:

I would rather use this
why use a pcall or xpcall if you don’t need to?

1 Like

Doing an if check is almost always more optimized than letting pcall swallow the errors for something as simple as this.

The only reason you should use pcall for is when you’re calling a function that sends HTTP requests to a website (HTTPService:GetAsync(), Player:IsInGroup(), ect.).

Also your code is faulty as you’re trying to index the index returned by for loop instead of the value and your script doesn’t account for any other BaseParts that isn’t a part:

for i,v in ipairs(script.Parent:FindFirstChild("Golden robot"):GetChildren()) do
	if v:IsA("Basepart") then
		v.CanTouch = false
	end
end
2 Likes

I was just asking because I remember hearing that it’s best to avoid if statements if possible, so I thought this might work.

Either you didn’t really understand what they meant by “avoiding” if statements (Like they probably were talking about if statements that were used poorly and have no reason to exist in code.) or whoever told that doesn’t understand how if statements work.

1 Like

if you aren’t using the variables just change it to

pcall(function()

makes no sense to have the “_, _” there

1 Like