Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare efficiency of two different LINQ statements

Tags:

c#

linq

I'm learning C# (background in C++), and I have a question about LINQ expressions. The following two functions both do the same thing (near as I can tell). The type of Wombats is System.Data.Linq.Table<Wombat>.

I'm interested to know

  1. Which is more efficient?
  2. Does it even matter?
  3. Is there something to be gained by returning IQueryqble, instead?
  4. Is there some etiquette here that prefers one of the three?

My guess is that the second is more efficient, but that it doesn't really matter unless there are millions of wombats in the wombat table. And returning an IQueryable doesn't seem to matter much since we're only ever returning a single wombat.

Thanks in advance!

    public static DBConnector.Connections.Wombat getWombat(String wombatID)
    {
        var db = getDBInstance();
        return db.Wombats.FirstOrDefault(x => x.ID.ToString() == wombatID);
    }

    public static DBConnector.Connections.Wombat getWombat(String wombatID)
    {
        var db = getDBInstance();
        var guid = new System.Guid(wombatID);
        return db.Wombats.FirstOrDefault(x => x.ID == guid);
    }
like image 264
BenDundee Avatar asked Jan 23 '13 17:01

BenDundee


1 Answers

This will depend completely on the DB's LINQ provider, and how it turns this into SQL. You could profile the resulting SQL (or even just inspecting the SQL trace) and determine which is more efficient.

I suspect that most providers will do better with the second option, as the actual check will be the same type - the query on the server will not need to convert each row to a string, and compare via a string comparison. This will likely allow the indexing to work properly, and make it far more efficient. That being said, a clever provider could do this conversion for you, in which case the two options may be identical.

like image 185
Reed Copsey Avatar answered Sep 22 '22 02:09

Reed Copsey