开发者

Which is faster? Loop over object properties or linq query?

开发者 https://www.devze.com 2023-03-20 21:57 出处:网络
Is this faster var query = from prop in object.GetType().GetProperties() where prop.Name == \"Id\" select prop;

Is this faster

var query = from prop in object.GetType().GetProperties()
            where prop.Name == "Id"
            select prop;

var singleProperty = query.SingleOrDefault();
//do stuff with singleProperty

than this?

var type = obje开发者_如何学Pythonct.GetType();
foreach(var prop in type.GetProperties())
{
  if(prop.Name == "Id")
   {
     //do stuff
   }
}

The other way around? Or are they the same?

Why and how would you know?

Sorry to be overly direct in my question. I prefer the first one but I don't know why or if I should.

Thanks.


Technically, the first case may allocate more memory and do more processing to generate the final result than the second case because of the intermediate data and LINQ abstractions. But the amount of time and memory is so negligible in the grand scope of things, that you're way better off making your code the most readable than the most efficient for this scenario. It's probably a case of premature optimization.

Here are some references why the first may be slightly slower:

  1. http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html
  2. http://ox.no/posts/linq-vs-loop-a-performance-test
  3. http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/23/c-linq-vs-foreach---round-1.aspx


The correct answer is: use Reflector to see what's being generated by the compiler.

That said, your LINQ query is using the same mechanism to retrieve the property list as your other snippet. It should technically be faster without involving the linq overhead. However, I'd expect the difference to be minimal (ie, unperceivable) , so this really comes down to a code readability and maintainability decision.

And I hate LINQ, so skip it.

Retrospective, one year later:

I've found that LINQ isn't the demon that I thought it was. I'm actually pretty impressed with its implementation, and spent quite a bit of time looking at the IL trying to find a legitimate reason not to like it. That said: LINQ-to-objects is pretty slick. However, future generations working on projects with a database: don't use this as a reason to perform all of your queries on the client instead of letting your database server do what it's very, very good at.


They are the same in terms of performance because LINQ makes use of deferred execution. However, a trivially (and irrelevant) larger amount of memory may go into the LINQ option.

Therefore, they are (effectively) identical in performance and behaviour!

I would go with the LINQ version for readability because I like LINQ but to each their own.

0

精彩评论

暂无评论...
验证码 换一张
取 消