Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

TIA.

like image 1000
benjy Avatar asked Sep 07 '09 19:09

benjy


People also ask

Why are database queries expensive?

The most common causes of expensive queries are: A lack of relevant indexes, causing slow lookups on large tables. Unused indexes, causing slow INSERT , UPDATE , and DELETE operations. An inefficient schema leading to bad queries.

How long does a database call take?

The query takes 20 to 500 ms (or sometimes more) depending on the system and the amount of data. The performance of the database or the database server has a significant influence on the speed.

Does SQL Server have for loop?

In SQL Server, there is no FOR LOOP. However, you simulate the FOR LOOP using the WHILE LOOP.


2 Answers

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
like image 194
Adam Batkin Avatar answered Sep 20 '22 17:09

Adam Batkin


In general, anything done in memory (for loop) is faster than the same thing done over a network (database call). However:

for i = 1 to num_users     get user from database end 

will be slower than

get users 1 to num_users from database (in one query) 

because it's the number of times you ask the database for something that really matters.

like image 43
Greg Hewgill Avatar answered Sep 16 '22 17:09

Greg Hewgill