Which is more expensive? For loop or database call?

前端 未结 7 1259
我在风中等你
我在风中等你 2020-12-29 05:13

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 looki

7条回答
  •  无人及你
    2020-12-29 05:30

    This greatly depends.

    A nested loop will be much faster than a database call if you just have a few hundred items. A database call involved usually a data transmission over lan or worse, internet. the query has to be parsed every time and so on.

    But if you have thousands or millions of items which are searched through in one database query then the sql query will be lots faster, since database systems are highly optimized to handle huge amounts of data. But do not forget to create indices for your tables.

    When in doubt, you should measure the time it takes for each method, and if it just gives you a better sense on how performance behaves.

提交回复
热议问题