Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLConnection optimization

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?

like image 285
Chris Miller Avatar asked Oct 15 '22 01:10

Chris Miller


2 Answers

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.

like image 66
Nickolay Olshevsky Avatar answered Nov 15 '22 13:11

Nickolay Olshevsky


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.

like image 22
Steve Madsen Avatar answered Nov 15 '22 14:11

Steve Madsen