Jump to content

which looping is faster?


Derpy

Recommended Posts

hi i have a question and i need your help to tell me which script would be better at performance

if we have table with 1000 indexes with some data, and we needed only 25 indexes of data,which would be faster?

1.

  
function myFunction() 
   for i,v in pairs(table) do 
      if i <= 25 then 
         outputChatBox(tostring(v)) 
      end 
   end 
end 
addEventHandler("onClientRender",root,myFunction) 
  

2. (i think this one is better at performance)

  
function myFunction() 
   for i = 1,25 do 
      outputChatBox(tostring(table[i)) 
   end 
end 
addEventHandler("onClientRender",root,myFunction) 
  

i think that first method would be catastrophic because it would loop 1000 indexes 60 times a second,while second method would loop only 25 indexes 60 times a second,am i correct??

Link to comment

Pairs is generally used when you want to process a list of elements but doesn't care about their order, you're right about the first example, it does loop through all 1000 entries. However, you can stop that after 25 entries with an else statement saying "break".

Last option is better tho as it only handles the counter and then access the table while the first one needs to store the whole table, assuming you want the data to be in order as well the second option looks even better. But about your specific examples, outputting 25*60 lines in chat box each second is going to be extremely slow no matter what. :wink:

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...