If .Count or .Count() is used several times on objects that implement ICollection (therefore with O(1) computational complexity, unless of course it has been overriden), is it better performance-wise (not memory wise), even for a very small difference, to cache the value in a temporary variable rather than accessing the property value each time it is needed?
If .Count or .Count() is used several times on objects that implement ICollection (therefore
Share
Yes, it could be (very slightly) faster, since the overhead of a method call, associated error checking, and (in the case of Count()) the dynamic type checking for ICollection have some amount of overhead.
Is it worth it though? That’s entirely up to you and your application. If you’re in a very tight inner loop, it might be worth it. Then again, on more recent .NET runtimes, this sort of trivial property will probably get inlined in such circumstances.
As always, let your profiler tell you where the hotspots are in your application.