2015-07-20 65 views
0

尋找更好的算法/技術來替換字符串變量中的字符串。我必須遍歷未知數量的數據庫記錄,並且對於每一個記錄,我需要替換字符串變量中的一些文本。現在它看起來像這樣,但必須有一個更好的辦法:替換字符串中文本的最佳方法

using (eds ctx = new eds()) 
{ 
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database"; 

    List<parameter> lstParameters = ctx.ciParameters.ToList(); 
    foreach (parameter in lstParameters) 
    { 
     string searchKey = parameter.searchKey; 
     string newValue = parameter.value; 
     targetText = targetText.Replace(searchKey, newValue); 
    } 
} 

從我的理解,因爲我在循環中寫targetText變量,一遍又一遍,這是不好的。然而,我不知道如何結構查找和替換...

感謝任何反饋。

+0

你擔心性能或者某些替代值可能會被替換('「asd」.Replace(「a」,「s」)替換(「s」,「d」)' )? – Prusse

回答

4

,必須有一個更好的辦法

字符串是不可變的 - 你不能「變」出來 - 所有你能做的就是創建一個新的和替換的變量值(這沒有你想象的那麼糟糕)。您可以嘗試使用StringBuilder作爲其他建議,但它不能100%保證提高您的性能。

可以通過targetText的「字」改變你的算法循環,看看是否有在parameters匹配,採取「置換」值,並建立一個新的字符串,但我懷疑額外的查詢將花費而不是多次重新創建字符串值。

在任何情況下,性能提高的兩個重要原則,應考慮:

  • 開始與您的應用程序的最慢部分首先 - 你可能會看到一些改善,但如果不提高整體性能顯着,那麼它並不重要
  • 唯一的方法來知道一個特定的變化會提高你的表現(以及多少)是嘗試這兩種方式並衡量它。
+0

爲什麼在某些情況下StringBuilder.Replace()是一個很好的選擇?它是可變的,開銷可能並不總是一個問題。請糾正我,如果我錯了 –

+0

@MarcWittmann它可能是,我會修改我的答案,使其不那麼絕對。 –

0

StringBuilder將具有更少的內存開銷和更好的性能,尤其是在大型字符串上。 String.Replace() vs. StringBuilder.Replace()

using (eds ctx = new eds()) 
{ 
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database"; 

    var builder = new StringBuilder(targetText); 

    List<parameter> lstParameters = ctx.ciParameters.ToList(); 
    foreach (parameter in lstParameters) 
    { 
     string searchKey = parameter.searchKey; 
     string newValue = parameter.value; 
     targetText = builder.Replace(searchKey, newValue); 
    } 
} 
0

其實,有一個更好的答案,假設你正在做大量的更新換代。您可以使用StringBuilder。如你所知,字符串是不可變的。正如你所說,你在你的循環中一遍又一遍地創建字符串。

如果您的字符串轉換爲StringBuilder

StringBuilder s = new StringBuilder(s, s.Length*2); // Adjust the capacity based on how much bigger you think the string will get due to replacements. The more accurate your estimate, the better this will perform. 

    foreach (parameter in lstParameters) 
    { 
     s.Replace(parameter.searchKey, parameter.value); 
    } 
    string targetString = s.ToString(); 

現在一個警告,如果你的列表只中有2-3個項目,這可能不是任何好轉。 this question的答案提供了一個很好的分析,您可以期待看到的性能改進。

相關問題