They shouldn’t and if they do they should affect both tests equally, so it wont matter as long as you compare the results to each other. Also I have a section in this post on how to set this kind of test up (towards the end): Proactive Testing: Profiling, Unit, and Fuzz testing
You should run each function enough times to take about one second total. The more times you run it the more precise the average will be. You should also try to do each run with different inputs, otherwise the result may be misleadingly faster. I will try and make an example of this.
local debugTools = require(game:GetService("ReplicatedStorage"):WaitForChild("DebugTools"))
local numberOfTestInputs = 1000
local numberOfTestRuns = 10000000
local testVectors = {}
local testOutput = {}
--Generate 1000 example inputs
for i = 1, numberOfTestInputs do
local newTable = {}
local number = math.random(1, 1000)
if math.random(1,2) == 2 then
table.insert(newTable, tostring(number))
else
table.insert(newTable, number)
end
table.insert(testVectors, newTable)
end
local function CopyFor()
local output = {}
local input = testVectors[math.random(1, numberOfTestInputs)]
for i, v in ipairs(input) do
output[i] = input[i]
end
table.insert(testOutput, output)
end
local function CopyForeachi()
local output = {}
local input = testVectors[math.random(1, numberOfTestInputs)]
table.foreachi(input, function(i, v)
output[i] = v
end)
table.insert(testOutput, output)
end
local function CopyClone()
local input = testVectors[math.random(1, numberOfTestInputs)]
local output = table.clone(input)
table.insert(testOutput, output)
end
local tstart = tick()
for i = 1, numberOfTestRuns do
CopyFor()
end
local ttotal = tick() - tstart
print("Time to run CopyFor " ..numberOfTestRuns.. " times: " ..ttotal)
--Clear table
testOutput = {}
tstart = tick()
for i = 1, numberOfTestRuns do
CopyForeachi()
end
ttotal = tick() - tstart
print("Time to run CopyForeachi " ..numberOfTestRuns.. " times: " ..ttotal)
testOutput = {}
tstart = tick()
for i = 1, numberOfTestRuns do
CopyClone()
end
ttotal = tick() - tstart
print("Time to run CopyClone " ..numberOfTestRuns.. " times: " ..ttotal)
The results say its the fastest but it doesn’t let you do things on the values as you copy it, so if you only need to copy its the fastest way. The other two would let you check the value and do some extra operation on it as you copy.
It should still be the fastest way but there will be a tiny bit of extra performance required to garbage collect the replaced tables. This cost is hard to measure and probably will be the same for each method. The difference is likely to be very small compared to other performance costs in your game.
FYI table.foreachi and table.foreach are both deprecated (or in the process of being deprecated). If you didn’t want to use table.clone and wanted a loop for something else: