0

i written code using for loop in 2 ways like below

first way

for(int i=0;i<myList.Items.Count;i++)
{
.....
.....
.....
}

second way

int itemsCount = myList.Items.Count;
for(int i=0;i<itemsCount;i++)
{
.....
.....
.....
}

in my view first way is better even though each and every incremnt of i value its checking (i< myList.Items.Count) because at runtime it simply replace myList.Items.Count with memeroy refrence so according to mine if i taken a new local variable to assign count of items its just a wastage of memory.

i want to know how it acts when i written code like above and tel me which way is more better in the view of performance aspect

Ramakrishna
  • 4,928
  • 3
  • 20
  • 24
  • If anything it's going to be a micro optimization, it's not worth worrying about unless it's actually causing you a problem. – Evan Trimboli Aug 23 '11 at 12:46

1 Answers1

0

I believe the first way is (in some compilers) the more optimal way in some circumstances.

You do not state a language, but it could be c# - so I will answer for that compiler. In C# I believe the former way of running is faster as it allows the compiler to ditch array bounds checking if you are accessing members of items in your loop. If you use an itemsCount variable it becomes more complicated for the compiler to track that the variable used in the loop has a safe value. This is only the case for a locally scoped array.

That argument may hold for other languages like Java that might use a similar looking loop.

Here is another question that addresses this question with for-loops in C#.

I would also add (following the comment from @Evan on the question) that optimization like this is seldom necessary, unless you have a specific need for a fast section of code. Write what is the most readable and less likely to cause issues first, then optimize where necessary.

Community
  • 1
  • 1
iandotkelly
  • 9,024
  • 8
  • 48
  • 67
  • Thank you for your answer, yes i am written code in c# only. in your explanation, you told that if we are using itemsCount variable it becomes more complecated to track that variable.. i did not understand that mean(according to my understanding for each time compiler must check that variable"itemsCount" it has been modified or not even it is not modified) – Ramakrishna Aug 23 '11 at 13:26
  • @Ramakrishna - basically the compiler can trust that if you are checking against .Count or .Length (for arrays) in each go around a for loop - then the value of i can never exceed the bounds of the list or array - so optimizes to remove bounds checking code. If you are checking against some arbitary variable, it cannot, without taking further steps to check the logic of your code do that. So even if your code is perfectly safe - the optimization is not performed. Your 'first example' is simply easier for the compiler to check that i can *never* exceed the bounds of the list. – iandotkelly Aug 23 '11 at 13:51