Max Index Optimization

Hello, I have a quick question regarding optimization. Would the first or second loop below be better in terms of efficiency? The second loop defines the max index of the table before looping so that, in theory, this does not have to happen 99 more times like in the first. However, I am unsure if this is practical as this value could already be stored in memory instead of it counting the number of contents in the table after each time it is called like I would think. Basically, I am wondering about how the # operation gets its value.

local tableVariable = {"contents1", "contents2", "contents3"}
for loopProgress = 1, 100 do
	for tableProgress = 1, #tableVariable do
		print(tableVariable[tableProgress])
	end
end

local tableLength = #tableVariable
for loopProgress = 1, 100 do
	for tableProgress = 1, tableLength do -- would using a variable for the max index be more efficient or just take up memory?
		print(tableVariable[tableProgress])
	end
end

In reality, both of these can be improved. Here’s another thing you can do:

for loopProgress = 1, 100 do
	for _, tableEntry in pairs(tableVariable) do
		print(tableEntry)
	end
end

Using pairs(), i create a iterator function to loop through all the table’s contents.

Also, you don’t need to predefine the variable, since it will be the same as #tableVariable.

Ah I see. Yes, this seems way better. Thank you.

1 Like