2014-03-25 19 views
2

參數我有一個方法傳遞方法變量作爲代碼優化

protected List<string> WrapInTwoLines(string text, int lineLimit) 
     { 
      ///There will be always two lines even first line can be empty and whole data goes to 2nd line 
      string[] originalLines = text.Split(new string[] { " " }, StringSplitOptions.None); 

      List<string> wrappedLines = new List<string>(); 

      StringBuilder actualLine = new StringBuilder(); 

      int index=0; 
      while(actualLine.Length + originalLines[index].Length < lineLimit) 
      { 
       actualLine.AppendFormat("{0} ",originalLines[index]); 
       index++; 
      } 
      wrappedLines.Add(actualLine.ToString()); 
      actualLine.Clear(); 

      while (index < originalLines.Length) 
      { 
       actualLine.AppendFormat("{0} ",originalLines[index++]); 
      } 
      wrappedLines.Add(actualLine.ToString().TrimEnd(' ')); 
      return wrappedLines; 
     } 

從環

for(int i=0; i< items.Count; i++) 
{ 
    length += items[i].Length + 2; 
    if (length > CHAR_LENGTH) 
    { 
     var list = WrapInTwoLines(items[i], CHAR_LENGTH - (length - items[i].Length + 2)); 
     subtitlesList.Add(s.Append(list[0]).ToString()); 

     s = new StringBuilder().AppendFormat("{0}{1}",list[1],separator); 
     length = s.Length; 
    } 
    else 
    { 
     s.AppendFormat("{0}{1}", items[i], separator); 
    } 
} 

我的方法創建新的每次迭代三個參考變量中被調用。我工作在這個代碼的優化和規劃實施方法如下

protected List<string> WrapInTwoLines(string[] originalLines, int lineLimit, List<string> wrappedLines, StringBuilder actualLine) 
      { 
       ///There will be always two lines even first line can be empty and whole data goes to 2nd line 
       //string[] originalLines = text.Split(new string[] { " " }, StringSplitOptions.None); 

       //List<string> wrappedLines = new List<string>(); 
wrappedLines.Clear(); 

       //StringBuilder actualLine = new StringBuilder(); 
actualLine.Clear(); 
    //Rest remains the same 
    } 

我認爲這將改善的代碼,但我不知道它將如何改善多少還是會提高代碼或沒有。我可以用什麼工具/技術來比較內存或速度方面的代碼優化? 另一個問題是,這是一個很好的模式來傳遞方法變量作爲參數(如上面的方法actualLine等)?

回答

3

此更改不會顯着提高性能。 Java和C#的垃圾收集器經過優化,可以非常好地收集像wrappedLines和actualLine這樣的小型短暫對象。當清除wrappedLines而不是創建新的時,GC仍然需要收集wrappedLines中包含的所有字符串。

除非您遇到性能問題,否則不要通過猜測性能優化來使代碼複雜化。如果沒有額外的參數,WrapInTwoLines方法更容易理解,而且容易出錯。

如果您遇到性能問題,請首先查看最內層的循環 - 這是最常執行的代碼。 AppendFormat需要對格式字符串進行運行時分析 - 這會比Append(「」).Append(originalLines [i])更糟糕。

就工具而言,我已經獲得了最好的結果,只是多次運行問題代碼並對其進行計時。有更復雜的工具可用,但我沒有發現它們的價值。始終運行多個計時試驗並將其平均,因爲單個試驗可能會出現偏差。