views:

56

answers:

3

Hello,

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..

+2  A: 

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.

Stefan Steinegger
okay... and by batch you mean transaction or its a diffrent story? another thing... should i care if those queries will be like 10% of all or even less...
ŁukaszW.pl
It has nothing to do with transactions. Transaction are used for isolation and to make several operations atomic. You can't write reliable database access without understanding transactions. Batches are a collection of queries which are sent at once to the database engine. Like a script.
Stefan Steinegger
If it simplifies your code, you shouldn't care too much about performance ... unless you identify a notable performance problem. If it does not influence your code too much, go for optimization.
Stefan Steinegger
+1  A: 

Your question is a bit thin on information... If the objects are in the same table, they should probably be fetched in one query, especially if you already know their ids.

Kaniu
those are objects from many tables... for example for some views i need to get not only usr but also its group and address...
ŁukaszW.pl
+1  A: 

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.

KeithS