简体   繁体   中英

Efficient way to retrieve multiple objects from database

quick qestion today... what is more efficient and is there a big diffrence in performance between those to SQL Server operations.

  1. select four objects from database in four separate select queries (just fetching them by id) in one single transaction, or

  2. select it in a single query (ofcourse more complicated, with joins).

I'll tell you that I'd rather like the first solution, but I need to know if it is much less efficient (if it is less eficient at all).

Thanks for any opinion..

Usually, multiple queries are less efficient, because there could be a network round trip and some other overhead for each. The most efficient you could do is retrieving exactly the data you need in the least number of queries needed.

On the other hand, if you use batching, you could perform multiple queries in one database round trip, which may take approximately the same time as accessing the objects in a single query.

if you only load a couple of objects, it doesn't matter much. Maintainability of the business logic, which most probably depends on the solution you choose, is more important.

The complexity of the joins and building objects could be done by an ORM. You don't have to implements such things yourself. With NHibernate you get the possibility to retrieve objects using complex queries or single instances by id. And - it also supports batching by ADO.NET and some other important performance improvements.

你的问题在信息上有点薄......如果对象在同一个表中,它们应该在一个查询中获取,特别是如果你已经知道它们的id。

Option 2 will be faster because it reduces the network "round trips". Submitting each query, then waiting while the server compiles a query plan and executes it is repeated for every query you submit; if you can get the information you want from one query, it will usually be faster. However, performance-wise it'd probably only be noticeable if you were querying hundreds or thousands of very "wide" records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM