[SOLVED] Which is more expensive? For loop or database call?


In general, which is more expensive? A double-nested for loop and one call to a database or a call to a database for each of N items in only one for loop?

Not looking for an answer down to microseconds, just a general idea of which direction I should take.



In general, the fewer times you hit the database, the better. There are a number of reasons for this, including:

  • The database will be able to optimize better if it can try to fetch everything all at once
  • You remove all of the overhead of communicating with the database multiple times, which can be quite significant

Answered By – Adam Batkin

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *