Reputation: 849
string id = (from c in context.Users
where c.u_id == Id
select c.u_id).SingleOrDefault();
1)How i can improve the performance for the above using Linq complied query for the above. We are limited to use .NET 3.5 only.
2)What will be performance gain using a complied linq query for the above code in terms of percentage?
Upvotes: 2
Views: 1529
Reputation: 1064274
A cheeky option would be: don't involve LINQ for such a trivial but performance-critical operation. For example, with dapper-dot-net:
string id = connection.Query<string>(
@"select u_id from Users where u_id = @id",
new { id = Id }).SingleOrDefault();
which completely avoids all the LINQ abstractions, leaning directly on the database (fully parameterless etc).
Upvotes: 1
Reputation: 835
Declare your compiled query like this:
static readonly Func<ENTITIES, YOUR_ID_TYPE, RETURN_VALUE_TYPE> compiledQuery =
CompiledQuery.Compile<ENTITIES, YOUR_ID_TYPE, RETURN_VALUE_TYPE>(
(ctx, Id) => (from c in ctx.Users
where c.u_id == Id
select c.u_id).SingleOrDefault();
Then in your code call your compiled query:
RETURN_VALUE_TYPE results = compiledQuery.Invoke(context, Id);
And regarding the performance improvement that can depend on several things, however keep in mind that in the scope of LINQ query execution, query compilation is an expensive part of the process. Any time you’re adding LINQ query logic to your LINQ to SQL- or Entity Framework-based applications, you should consider precompiling the queries and reusing them.
Upvotes: 1
Reputation: 564931
You would create the compiled query via:
Func<YourContextType, int, string> query = CompiledQuery.Compile(
(YourContextType context, int id) =>
context.Users.Where(u => u.u_id == id).Select(u => u.u_id)
.SingleOrDefault()
);
You would then use this as:
string resultId = query(context, Id);
As for the performance gain, this may be significant, but it may also be minimal. It really depends on how quick the query is being performed, and how often you can reuse the compiled query. In many cases, using the cmopiled query is actually slower, as the overhead of compilation doesn't make up for the speed gains. You would need to measure to determine if this is worth the effort.
Note that, if you know you only have one unique ID, you can also potentially speed up your original query merely by using FirstOrDefault()
instead of SingleOrDefault()
.
Upvotes: 3