What's the difference between "in" compared to using ipairs/pairs

So, I’ve been using “pairs” for the longest for looping through tables, but I was told
it was not needed and I could just use “in” for the same result while making the code faster.

I was wondering what’s the difference between using in with no ipairs/pairs as it
seems to achieve the same result

local Table = {}
local pre, post
local finalPrint = ""

wait(3) -- loading time

-- generating table with 10,000 elements
for c=1,10000,1 do
	table.insert(Table, math.random(1,100))
end

pre = tick()
for i,v in pairs(Table) do
	finalPrint = finalPrint .. i .. v .. "\n"
end
post = tick()

print(finalPrint)
print("Time taken: " .. (post-pre))

-- in  (with no pairs/ipairs)
-- Time taken: 0.1148381233215332

-- in with ipairs
-- Time taken: 0.13102221488952637

-- in with pairs
-- Time taken: 0.13428735733032227

Thanks!

1 Like

Generalized iteration (for loops without pairs or ipairs) is a luau feature that was added a while back.

According to Syntax - Luau it essentially behaves like pairs.

The default iteration order for tables is specified to be consecutive for elements 1..#t and unordered after that, visiting every element; similarly to iteration using pairs, modifying the table entries for keys other than the current one results in unspecified behavior.

It is very slightly quicker, and is simpler making it easier to read. I generally think it should be used in all cases except if you need some of the very specific functionality of ipairs or want backwards compatability with lua.

1 Like

Thank you so much!, this helped alot.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.