Which is better?

Which one would be more performant?

local myTable = {}

myTable[1] = 1
myTable[2] = 2
myTable[3] = 3
myTable[4] = 4
myTable[5] = 5

-- pretend these are objects that are being gradually added throughout gameplay, such as workspace.part, not numbers

if myTable[cast.instance] then
  -- do something
end
local myTable = {}

table.insert(myTable, 1)
table.insert(myTable, 2)
table.insert(myTable, 3)
table.insert(myTable, 4)
table.insert(myTable, 5)

-- pretend these are objects that are being gradually added throughout gameplay, such as workspace.part, not numbers

if table.insert(find, cast.Instance) then
  -- do something
end

Thanks!

First method is faster
image

Code used
local a1 = tick()

for i = 1, 10000000 do
	local myTable = {}
	myTable[1] = 1
	myTable[2] = 2
	myTable[3] = 3
	myTable[4] = 4
	myTable[5] = 5

	if myTable[4] then
		local a = true
	end

end

local a2 = tick()
-------------------------------------------

local b1 = tick()

for i = 1, 10000000 do
	local myTable = {}
	table.insert(myTable, 1)
	table.insert(myTable, 2)
	table.insert(myTable, 3)
	table.insert(myTable, 4)
	table.insert(myTable, 5)
	-- pretend these are objects that are being gradually added throughout gameplay, such as workspace.part, not numbers
	if table.insert(myTable, 4) then
		local b = true
	end
end

local b2 = tick()

---------------------------

print("Time for method 1:", a2-a1)
print("Time for method 2:", b2-b1)

I seem to have messed up xD

Could you run this:

local a1 = tick()

for i = 1, 10000000 do
	local myTable = {}
	myTable[1] = 1
	myTable[2] = 2
	myTable[3] = 3
	myTable[4] = 4
	myTable[5] = 5

	if myTable[4] then
		local a = true
	end

end

local a2 = tick()
-------------------------------------------

local b1 = tick()

for i = 1, 10000000 do
	local myTable = {}
	table.insert(myTable, 1)
	table.insert(myTable, 2)
	table.insert(myTable, 3)
	table.insert(myTable, 4)
	table.insert(myTable, 5)
	-- pretend these are objects that are being gradually added throughout gameplay, such as workspace.part, not numbers
	if table.find(myTable, 4) then
		local b = true
	end
end

local b2 = tick()

---------------------------

print("Time for method 1:", a2-a1)
print("Time for method 2:", b2-b1)

Thanks!

image
this is my result :p

the difference between

myTable[5] = 5

and

myTable[5] = true/false

is negligible, sometimes one is faster, and sometimes the other is faster.
However, it is very clear that

if myTable[4] then
	local a = true
end

is much faster than

if table.find(myTable, 4) then
	local a = true
end

Thanks!

Your result is what is expected. The lower the time it outputs, the better.

1 Like