ipairs seems to work a lot faster than pairs

Hybrid Dog
Member
 
Posts: 2460
Joined: Thu Nov 01, 2012 12:46

ipairs seems to work a lot faster than pairs

by Hybrid Dog » Fri May 27, 2016 13:49

People told me that pairs works faster than ipairs, but according to my benchmark test it's the other way round.
And using a simple for loop works ~10 times faster (see iterdpairs).
Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
Code: Select all
local function do_test()
   local t = {}
   for i = 1,10000 do
      t[i] = math.random(100)
   end

   local t0 = benchmark_function(function()
      for _,i in ipairs(t) do
         local v = i
      end
   end)

   local t1 = benchmark_function(function()
      for i = 1,#t do
         local v = t[i]
      end
   end)

   local t2 = benchmark_function(function()
      for _,i in pairs(t) do
         local v = i
      end
   end)

   return {ipairs=t0, iterat=t1, pairs=t2, iterdpairs=t1/t2}
end

local function do_tests()
   print(dump(do_test()))
   print(dump(do_test()))
end

minetest.register_chatcommand("dot", {
   func = do_tests
})

results:
Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
Code: Select all
{
   pairs = 8823.1911883084,
   iterdpairs = 12.10008838753,
   ipairs = 70913.929086071,
   iterat = 106761.39323861
}
{
   pairs = 8822.7044394013,
   iterdpairs = 12.399933155525,
   ipairs = 69546.978397662,
   iterat = 109400.94529953
}
{
   pairs = 8786.1178038755,
   iterdpairs = 12.375191603071,
   ipairs = 70601.752893865,
   iterat = 108729.89127011
}
{
   pairs = 8832.5981167857,
   iterdpairs = 12.290935238273,
   ipairs = 69513.548161937,
   iterat = 108560.89143911
}
{
   pairs = 15651.233929023,
   iterdpairs = 6.8358941866598,
   ipairs = 69837.185732664,
   iterat = 106990.17902946
}
{
   pairs = 16002.043941748,
   iterdpairs = 6.6102360942443,
   ipairs = 71695.749064878,
   iterat = 105777.28844542
}

l use luajit of course.
The benchmark function from http://dev.minetest.net/Lua_Optimizatio ... nchmarking is omitted in the code.
 

User avatar
stu
Member
 
Posts: 737
Joined: Sat Feb 02, 2013 02:51
GitHub: stujones11

Re: ipairs seems to work a lot faster than pairs

by stu » Fri May 27, 2016 17:50

What happens if the table has non-integer keys?

Edit: Ignore that, I guess you wouldn't be using ipairs then.
 


Return to Modding Discussion

Who is online

Users browsing this forum: Google [Bot] and 18 guests

cron