views:

137

answers:

3

I'm trying to understand NSURLConnection performance on a 3G network from an iPhone. I have the following test code

-(void)doTest2 {
     max = 5;
     NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
     NSURLRequest *request2 = [[[NSURLRequest alloc] initWithURL:url] autorelease];  
     NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request2 delegate:self];  
     self.startDate = [NSDate date];
     if (conn)   
     {  
        receivedData = [[NSMutableData data] retain];  
     }  }   



- (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
       self.endDate = [NSDate date];
       NSTimeInterval interval = [self.endDate      timeIntervalSinceDate:self.startDate];
       NSLog(@"Time:%f Size:%u", interval, [receivedData length]);
      [receivedData release];  

       count = count + 1;
       if (count == max) { 
          count = 0;
          sleep(3);
       }
       self.doTest2;}

The very first request is slow (over 1 second). Requests 2-5 are fast (under .25 seconds). If I sleep for 3 or more seconds, the first request after the sleep is slow. But if I sleep for less than 3 seconds, it's fast. Any ideas why?

A: 

There can be a number of reasons: on first request TCP stack needs to resolve DNS name of google.com, after that it is cached. Also, it can need some time to initialize 3G network.

Nickolay O.
A: 

I think this link might be helpful: http://developer.apple.com/mac/library/samplecode/CacheInfo-MacOSX/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007751

It demonstrates the caching behaviour in cocoa.

Leg10n
+1  A: 

I can't find a link to support my theory, but at WWDC 2010, Apple engineers repeatedly stressed power consumption on iPhone, stating that the 3G spec required that the radio be kept in a high power state for a period of time after the last transmission. My guess is that waiting 3 seconds allows the radio to idle, and the next transmission requires it to power back up and re-negotiate with the cell tower.

Steve Madsen