According to the following unit test methods, StringBuilder is far slower than String.Replace, how come every one saying StringBuilder is faster? Am I missing something?
[TestMethod]
public void StringReplace()
{
DateTime date = DateTime.Now;
string template = File.ReadAllText("file.txt");
for (int i = 0; i < 100000; i++)
{
template = template.Replace("cat", "book" );
template = template.Replace("book", "cat");
}
Assert.Fail((DateTime.Now - date).Milliseconds.ToString());
}
[TestMethod]
public void StringBuilder()
{
DateTime date = DateTime.Now;
StringBuilder template = new StringBuilder(File.ReadAllText("file.txt"));
for (int i = 0; i < 100000; i++)
{
template.Replace("cat", "book");
template.Replace("book", "cat");
}
Assert.Fail((DateTime.Now - date).Milliseconds.ToString());
}
Here is the result:
StringReplace - 335ms
StringBuilder - 799ms
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…