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 = object.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: