Is for i,v in next faster than for i,v in pairs?

So, i was messing around using for i,v in pairs and for i,v in next and for me i though that for i,v in next was faster, i just want somebody to confirm if this is actually true cuz i kinda need a faster i,v in a script im making

1 Like

The difference between the two is basically irrelevant because pairs just returns next and 2 other variables, and unless there are backend optimizations on roblox’s side taking effect, the difference will be basically nothing.

1 Like

But by that do you mean that next will actually be faster?

You’re worrying about the wrong issues. Both are as fast as each other and it isn’t about the speed but the application of it.

Oh, i just wanted to know if something was faster, cuz im making a kill all script for my game’s admin gui and i wanted to get all players at the same, or almost the same time, bc the script is kinda long

Because computers are pretty good in numbers.

1 Like

You can compare the speed difference by using a script like this:

local startTickA = tick()
-- Method A (In your case "next()")
print("Method A took "..tostring(tick() - startTickA).." seconds.")

local startTickB = tick()
-- Method B (In your case "pairs()")
print("Method B took "..tostring(tick() - startTickB).." seconds.")

Now you can decide which function you would like to use having the speed in mind.

1 Like

There is basically no difference. In fact, the native pairs() function itself uses the native next() function, id est the pairs() function returns the next function. pairs() is literally defined as:

function pairs(t)
    return next, t, nil
end

You can read more about it on Lua’s official website: Programming in Lua : 7.3

I tried benchmarking it a while ago and the difference fluctuates often; there is no clear winner. You should just use whatever you prefer, for example, if you think typing out next, t is faster than pairs(t) then yeah go ahead, no one’s stopping you. Some people still prefer to use pairs for consistency since ipairs() also exist

7 Likes

Thx for all the help! its kinda a low difference but now i know, i wont mark anything as solution as this is kinda discussion but everything was useful to me!

ipairs() according to this benchmark is more efficient than pairs(), albeit the difference is essentially negligible.

That’s because computers are pretty good in numbers. And ipairs runs through iterators which are numbers, pairs can also be ran through dictionaries because it supports string which takes a longer process than ipairs, which is why ipairs is faster than pairs.

1 Like

I know why it’s faster, I was just providing the benchmark.

2 Likes

I know I was just explaining to other users.

1 Like