2013-08-23 125 views
1

我有一段代碼,我試圖優化。該方法正在使用很多,所以任何小小的改進都會大大提高性能。優化Objective-C代碼

- (CGRect)calculateRectForItemAtIndex:(NSIndexPath*)path { 
    //Get the x position stored in an NSMutableArray 
    double x = [self.sectionXPlacementArray[path.section] doubleValue]; 
    double y = 0; 
    double height = 0; 

    //If this is the first row it is a header so treat it different 
    if (path.row == 0) { 
     height = self.defaultHeaderHeight; 
     y = 0; 
    } 
    else { 
     height = self.defaultHeight; 
     //Calculate the Y placement 
     y = (path.row-1)*self.defaultHeight+self.defaultHeaderHeight; 
    } 
    //Build and return a CGRect 
    return CGRectMake(x, y, [self.headerSizes[self.headers[path.section]] doubleValue],height); 
} 

下面是一些更多的信息:

1)headerSizesNSMutableDictionary,看起來像這樣:

{ 
    Header1 = 135; 
    Header2 = 130; 
    Header3 = 130; 
} 

2)headersNSMutableArray看起來像這樣:

(
    Header1, 
    Header2, 
    Header3 
) 

應用程序中的這些值w生病不是Header_。它們將是動態NSStrings,如「城市」或「國家」。 headerSizes將包含應爲每個標頭使用的寬度。

+10

您確定此方法實際上會減慢您的應用程序嗎? – bdesham

+2

沒有辦法,這是你的瓶頸 – Vik

+0

在你的例子中,性能瓶頸並不明顯。但是,我很好奇 - 這看起來很像一張桌子。這就是說,如果性能是你關心的話,那就用UITableView吧。 Apple對這種類型的事物有各種經驗,比如排隊等等。 – Jeremy

回答

2

另一個人評論說,這看起來不像是一種會減慢速度的方法。它涉及鋪設東西,對吧?或者畫什麼東西?這不應該經常發生(即每秒60次,在最差的)。你確實有任何證據,這是瓶頸?就像,你是否通過Instruments中的Profiler模板運行你的代碼?這在數據的反向調用樹視圖中顯示爲排名第一的頂級方法?

這就是說,這裏沒有太多東西需要削減。我盡了最大的努力...

- (CGRect)calculateRectForItemAtIndex:(NSIndexPath*)path 
{ 
    //Get the x position stored in an NSMutableArray 
    const NSUInteger pathSection = path.section; 
    const NSUInteger pathRow = path.row; 
    const float x = [self.sectionXPlacementArray[pathSection] floatValue]; 
    float y = 0; 
    float height = 0; 

    //If this is the first row it is a header so treat it different 
    if (pathRow == 0) { 
     height = self.defaultHeaderHeight; 
     y = 0; 
    } 
    else { 
     const float defaultHeight = self.defaultHeight; 
     height = defaultHeight; 
     //Calculate the Y placement 
     y = (pathRow-1)*defaultHeight+self.defaultHeaderHeight; 
    } 
    //Build and return a CGRect 
    return CGRectMake(x, y, [self.headerSizes[self.headers[pathSection]] floatValue], height); 
} 
+0

好吧,使用花車而不是雙打應該是一個改進,幾乎沒有精度損失。 – Sulthan

+2

我認爲這種差異是微不足道的,但是,這個問題/答案有點兒是假的,因爲這種方法是瓶頸,沒辦法,如果是這樣,那麼無論怎麼稱呼它都是「doin 「錯了。」 (PS:我想ARM在ARM上的懲罰可能會高於x86_64,不想拆解它並計算指令和週期:)) – ipmcc

+0

我絕對同意。我的評論將只對codereview.stackexchange :)有效:)使用'double'是很奇怪的,每個類型都被定義爲'CGFloat'。 – Sulthan