• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Arrays & For Loops
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Arrays & For Loops


  • Subject: Arrays & For Loops
  • From: Bill Bumgarner <email@hidden>
  • Date: Tue, 25 Mar 2003 09:21:10 -0500

On Tuesday, Mar 25, 2003, at 09:02 US/Eastern, email@hidden wrote:
for (i = 0; i < [myArray count]; i++) {
....
....
}
--- A reasonable question, but the [myArray count] is messaged only
once, because that's the way C for loops work. Read the details on FOR
loops - the arguments are evaluated only once to determine parameters,
then the loop is executed.
For that reason it's bad practice to modify the termination condition
([myArray count] in this case), or the increment condition (i++), from
within the loop.

That is incorrect. Consider:

#include <stdio.h>

static int max = 3;

int test(int anIndex) {
fprintf(stdout, "Testing %d\n", anIndex);
return anIndex<max;
}

int main (int argc, const char * argv[]) {
int i;
for(i=0; test(i); i++)
fprintf(stdout, "Doing %d\n", i);
return 0;
}

The output is...

Testing 0
Doing 0
Testing 1
Doing 1
Testing 2
Doing 2
Testing 3

... which indicates that the test and increment "arguments" (not arguments -- expressions) of the for() loop are executed once per pass through the loop with the "test" expression being evaluated one "extra" time for the pass that terminates the loop.

As such, (i<[myArray count]) as the test in a for loop will cause -count to be invoked for every pass through the loop. As someone else pointed out, the performance hit caused by the method invocation will very likely be completely irrelevant.

In the rare case that it is not or in the much more common case where Programmer Hubris insists upon optimizing something prior to determining that it is actually a performance issue, you can always do something like the following.

int max = [myArray count];
int i;
for (i=0; i<max; i++) {
....
}

Alternatively, just use an enumerator and be done with it:

NSEnumerator *arrayEnumerator = [myArray objectEnumerator];
id anObject;
while(anObject = [arrayEnumerator nextObject]) {
....
}

b.bum
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Prev by Date: Re: 3 obj-c/cocoa beginner q's
  • Next by Date: Re: 3 obj-c/cocoa beginner q's
  • Previous by thread: popup buttons and notifications
  • Next by thread: Re: 3 obj-c/cocoa beginner q's
  • Index(es):
    • Date
    • Thread