The First Rule of Performance Tuning Five on Friday
Oct 08

Creating objects can be very expensive in terms of performance. This is especially true for UIControls that are also added to a UIView. Instead create a number of objects once and reuse them when needed.

Here’s a code snippet from a book reader application that lays out each text paragraph as it’s own UILabel. Since each page has a varying number of paragraphs each with varying number of lines of text I initially created the necessary UILabels each time a page was rendered. Bad idea!

Now I have an array (often called an object pool) of UILabels that have been created and added to the page UIView. Initially the hidden property is set to YES for all these labels. When a page is rendered a UILabel is picked from the pool, initialized with the appropriate text, location and size. And the hidden property is set to NO to display the label.

// Add new text to existing labels
for (int i = 0; i < MAX_LABELS; i++) {
   UILabel *textLabel = [textLabels objectAtIndex:i];
   if (i < [currentPage.paragraphs count]) {
      NSString *paragraph = [currentPage.paragraphs objectAtIndex:i];
      CGSize textSize = [paragraph sizeWithFont:textFont
 						constrainedToSize:CGSizeMake(PARAGRAPH_WIDTH, 1000)
 						lineBreakMode:UILineBreakModeWordWrap];
      textLabel.font = textFont;
      textLabel.frame = CGRectMake(PARAGRAPH_LEFT_MARGIN, yOffset, PARAGRAPH_WIDTH, textSize.height);
      textLabel.hidden = NO;
      textLabel.text = paragraph;
      yOffset = yOffset + textSize.height + PARAGRAPH_SPACING;
   } else {
      textLabel.hidden = YES;
      textLabel.text = @"";
   }
}

 
In addition to speed performance improvements this solution also has the significant benefit of managing memory much better. 

written by Nick \\ tags:

Leave a Reply