我刚刚进入函数式编程并试图了解何时应该使类/属性可变。
当处理大量字符串连接时,我们知道最好使用 StringBuilder,例如:
using System;
using System.Diagnostics;
using System.Text;
namespace ConsoleApplication3
{
internal class Program
{
private static string myStr;
private static readonly StringBuilder mySb = new StringBuilder();
private static void Main(string[] args)
{
Profile("+", 100000, () => myStr = myStr + "a"); // Takes 2236 ms
Profile("SB", 100000, () => mySb.Append("a")); // Takes 1 ms
}
private static void Profile(string description, int iterations, Action func)
{
// clean up
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// warm up
func();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
func();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
}
}
这是众所周知的情况,在这种情况下,通过与运算符连接字符串的性能要高得多。我的假设是通过创建更少的字符串来实现更好的性能。StringBuilder
+
StringBuilder
性能和不变性之间是否存在平衡,或者这种情况是出于某种原因的例外?