Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am fetching data from the database using entity framework and linq queries. I am wondering about the performance of getting data.

Here is my code. I just want to check that a Well exists in database or not. Database table has 15 columns and number of rows are unknown.

internal static bool WellExists(string name, DatabaseContext context)
{
    var name = context.Wells.Where(w => w.name == name).Select(w => w.name).FirstOrDefault();
    return !string.IsNullOrEmpty(databaseUwi);
}

Here my point of concern is the line in which I am using linq queries. In this I am using a Where, then Select and then FirstOrDefault. Another solution is using FirstOrDefault only.

var well = context.Wells.FirstOrDefault(w => w.name == name);
return !(well == null);

The first query will get only selected data (Select) which is not required. Which solution performance is better?

share|improve this question
3  
I suggest perhaps profiling the query and seeing what the underlying SQL is. LinqPad is quite good for this, or I believe you should be able to see the SQL in debugger. In spite of that I think you will find all your examples generate the same underlying SQL –  dreza May 9 at 9:51
6  
If you want to know the performance of something measure it and then you'll know. This question is like saying "I have a horse, does anyone know how fast it runs?" How should we know? If you have two horses and want to know which is faster, race them, don't ask strangers on the internet which one will win the race. –  Eric Lippert May 9 at 13:46

1 Answer 1

up vote 13 down vote accepted

You can try the .Any function on IQueryable. It is made for checking if there are any records.

Remember that .Any() has an overload that takes an expression, making the solution

internal static bool WellExists(string name, DatabaseContext context)
{
    return context.Wells.Any(x => x.Name == name);
}

I'm going to add a comment about your code as well. In the second example you have return !(well == null). This obfuscates the meaning of the code a bit, and would be clearer if you write return well != null;

share|improve this answer
3  
+1 for Any() suggestion –  dreza May 9 at 9:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.