Table.foreach or for pairs()?

hi, I was messing around with tables and I see

local TestTable = {'test','test2','Test345'}

table.foreach(TestTable,function(-,key)
warn(key)
end)

is equal with:


local TestTable = {'test','test2','Test345'}

for _,Key in pairs(TestTable) do
      warn(Key)
end

i have a question, is one faster than other?

4 Likes

foreach runs in no defined order, and from my understanding, does not yield the current thread, whereas a for loop will block the thread, and will run in a defined order. If you’re familiar with JS, then foreach is the equivilant of using a promise.

Measuring speed/performance/efficiency for this is difficult as you can see.

13 Likes

Don’t use either foreach or pairs. You’re working with an array so use ipairs instead. ipairs is designed to iterate over contiguous arrays. It is currently the fastest iterator, iterating at an i++ indice basis where keys are known and it shows that you’re working with arrays.

foreach is deprecated and pairs is designed to iterate through tables where keys are arbitrary and unknown. A recent update to pairs seems to not call next internally though pairs is intended to iterate when keys can be any valid datatype. pairs also does not iterate in successive order. If order is important to you, then you should be working with ipairs.

Really though, speed difference is negligible here.

11 Likes

This is incorrect. In Lua 5.1 table.foreach works as another next wrapper that does yield the thread.

8 Likes

I dont mean to bump this, but I wanted to mention that I see nothing in the docs that states foreach is deprecated.

If it is in fact deprecated, what was the reasoning behind the decision?

3 Likes

It’s a question for clarification that’s relevant to the thread so it doesn’t quite count as a bump, but you probably could’ve messaged me privately if you were worried about bumping.

The Roblox docs for table are somewhat out of touch with vanilla Lua considering all the differences, modifications to the language and so on. I recall that they were originally marked as deprecated: if they weren’t or that was reverted, that’s something that needs to be updated.

foreach/i is deprecated because of the for operator, which effectively supersedes foreach/i and allows for extensions such as numeric for loops and custom generators. The for operator handles everything that foreach/i can, so the functions are effectively useless and redundant.

They were deprecated in Lua 5.1 and further.

6 Likes