Reputation: 1334
I have a class with a collection of methods in, and I was wondering if there is any performance bonus of using methods over properties?
Some of the methods are fairly complex, but basically return an IEnumerable collection of objects, while others are a simple return values.Where(x => x.property == "comparison")
Linq query.
Examples
Method:
public IEnumerable<PenDataRow> ActivePens() => Pens.Where(x => x.Status == "Active");
Property:
public IEnumerable<PenDataRow> ActivePens => Pens.Where(x => x.Status == "Active");
Would it be better to mark them as properties or methods?
Upvotes: 12
Views: 5238
Reputation: 19765
There is no performance difference per se, but I would argue that users of your class might 'expect' one. That is, a property like ActivePens
might be perceived to be 'lighter-weight' than a method like GetActivePens()
. I try to write methods to get values of things that are more expensive. It's very subjective.
There may also be debugger-impact too - hovering over a property in a class in the debugger might call that property and incur an expensive operation to show you the tooltip.
Upvotes: 4
Reputation: 437336
Properties are implemented as methods under the hood, so there is absolutely no performance difference. The guidelines for choosing between a property and a method are semantic.
Upvotes: 21
Reputation: 108975
A property is just one or two methods with specific naming and metadata.
Therefore the overhead is the same, as are the opportunities for JIT inlining..
Upvotes: 4
Reputation: 5801
Nope, no performance gain whatsoever, because they are also methods that help expose your private fields, in a more elegant way.
Upvotes: 2