Question

Is there any or noticeable performance decrease; when using linq queries on string properties vs method calls to get that string value; in an IEnumarable list? If not; is there any other queryable interface for linq that makes performance difference?

What I mean is;

public class MyForm
{
    public string FormName {get; set;}

    public string GetFormName()
    {
      return FormName;
    }
}

List<MyForm> MyFormList;

//1)
var result = MyFormList.Where(f=>f.FormName=="SalesForm").SingleOrDefault();

//2)
var result = MyFormList.Where(f=>f.GetFormName()=="SalesForm").SingleOrDefault();

Is there any noticeable performance decrease between option 1 and option 2? Is there any technique that .NET using for string properties to be indexed for best performance when linq query is executed other than IEnumurable; that linq can still query?

My assumption; since IEnumarable just iterates all items; there is no much difference to access string property vs gettting the string value by calling the relevant method.

Am I right?

Was it helpful?

Solution 2

Yes, IEnumerable will do linear search with O(n) complexity. There is unlikely to be measurable difference between filed, property or method call returning a string (make sure to measure if actually important).

If you need lookup that is faster - dictionary is the better choice with O(1) lookup.

Notes

  • if you are querying DB with Linq-to-SQL such property access will be translated into SQL query and likely be optimized by SQL to be close to O(1) on indexed fields.
  • property is a method - so automatic property and method directly returning backing filed should have the same performance. In your sample you have method that returns value of property that in turn returns value of backing field which may cause some difference, but there is good chance that both calls will be inlined by JIT anyway.
  • you can implement your own IQueryable source to provide optimized search/where methods and get queries compiled into Queryable extension calls instead of Enumerable ones.

OTHER TIPS

Properties are methods. A property is translated into a (pair of) method(s) at compile time. (Often the jitter will then inline these methods, so there's not really any call-stack performance penalty for this).

Iterating an IEnumerable will look at each item. There are cases where it may build a HashSet behind the scenes, but it still needs to do that for each item in the sequence at least once, whether property or method, and none of the included IEnumerable operators (to my knowledge) treat the two any differently.

What you might see difference is in any extra the work the method might do or not do to get the result you need. If the property or the method themselves are inherently faster, then those small differences can add up when called over and over during a linq expression evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top