Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, when using List<T>, is it good to cache the Count property, or is the property fast enough?

Tags:

c#

In other words, which of the following would be faster, if any?

List<MyClass> myList;
...
...
foreach (Whatever whatever in SomeOtherLongList)
{
  ...
  if (i < myList.Count)
  {
    ...
  }
}

or

List<MyClass> myList;
...
...
int listCount = myList.Count;
foreach (Whatever whatever in SomeOtherLongList)
{
  ...
  if (i < listCount)
  {
    ...
  }
}

Thanks :)

like image 656
Stephen Oberauer Avatar asked Sep 08 '10 10:09

Stephen Oberauer


1 Answers

The Count is just an integer. it doesnt get calculated when you ask its value. it's 'pre-calculated' so it's the same. option 1 is more readable :)

like image 162
Stefanvds Avatar answered Sep 19 '22 08:09

Stefanvds