I have an application that iterates over an array every step and I seem to be getting surprisingly slow results when the array is empty. So, I investigated with some follow-up tests that went something like this:
NSMutableArray* ar = [NSMutableArray array];
double time = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 10000; i++)
{
for (NSObject* obj in ar)
{
[obj retain];
[obj release];
}
}
time = CFAbsoluteTimeGetCurrent() - time;
printf("Empty Time: %1.12f", time / 10000.0f);
time = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 10000; i++)
{
if ([ar count] > 0)
{
for (NSObject* obj in ar)
{
[obj retain];
[obj release];
}
}
}
time = CFAbsoluteTimeGetCurrent() - time;
printf("Checked Time: %1.12f", time / 10000.0f);
I tried this for 100 | 1,000 | 10,000 iteration intervals with the following results:
Empty Time: 0.000000039935 //100
Checked Time: 0.000000020266 //100
Empty Time: 0.000000018001 //1000
Checked Time: 0.000000011027 //1000
Empty Time: 0.000000015503 //10000
Checked Time: 0.000000008899 //10000
Strangely, this shows that having the simply count check significantly improves performance on low-iteration runs (probably because of caching schemes). This is absolutely astonishing for me as I expected the Objective-C compile/runtime to already do this check whenever a foreach loop is executed! Does anyone have any idea why this might be the case and if there is any way to squeeze even more performance out of this loop setup? Thanks!