I’m not sure if it actually improves the speed or not because I know when you use :GetChildren())
it returns a table of the instance, same with :GetDescendants()
, etc., if it really does improves the speed then I might have to change most of the for loop that I have used.
function self.GetPlayerAssets()
local images = Player:FindFirstChild("Images")
local sounds = Player:FindFirstChild("Sounds")
for _, imageLabel in images:GetChildren() do
print(imageLabel)
end
for _, imageLabel in pairs(images:GetChildren()) do
print(imageLabel)
end
end
Okay so I ran a benchmark and the first option (__iter
metamethod) seems to be very slightly faster in general, but not enough to warrant a change in entire codebase:
1 Like
I also did some test but I don’t know if this is even called testing, I’d say there are no difference.
Code
repeat wait(1) until game:IsLoaded()
game.Players.LocalPlayer.CharacterAdded:Wait()
local array = {}
local round = math.round
local insert = table.insert
local arrayTimeAverage = {}
local parisTimeAverage = {}
for i = 1, 50000000 do
insert(array, i)
end
function checking(i)
if i then
local k = i + i
if i + i == k then
k = i
end
end
end
function arrayTest()
local delta = tick()
for _, i in array do
checking(i)
end
return round((tick() - delta) * 1000)
end
function pairsTest()
local delta = tick()
for _, i in pairs(array) do
checking(i)
end
return round((tick() - delta) * 1000)
end
function getAverageTime(timeArray)
local average = 0
for _, delta in timeArray do
average += delta
end
average /= #timeArray
return average
end
for i = 1, 5 do
local timeDiff = arrayTest()
insert(arrayTimeAverage, timeDiff)
print(string.format("Array Time: %ims", timeDiff))
wait(1)
end
print(string.format("Average Time: %ims", getAverageTime(arrayTimeAverage)))
for i = 1, 5 do
local timeDiff = pairsTest()
insert(parisTimeAverage, timeDiff)
print(string.format("Pairs Time: %ims", timeDiff))
wait(1)
end
print(string.format("Average Time: %ims", getAverageTime(parisTimeAverage)))
Array Time: 1257ms
Array Time: 1271ms
Array Time: 1259ms
Array Time: 1255ms
Array Time: 1253ms
Average Time: 1259ms
Pairs Time: 1252ms
Pairs Time: 1256ms
Pairs Time: 1255ms
Pairs Time: 1252ms
Pairs Time: 1254ms
Average Time: 1253ms