. , . :
public static string BenchmarkMethod(Action method, int iterations)
{
var watch = new Stopwatch();
var results = new List<TimeSpan>(iterations);
for (int iteration = 0; iteration < iterations; iteration++)
{
watch.Start();
method();
watch.Stop();
results.Add(watch.Elapsed);
watch.Reset();
}
var builder = new StringBuilder();
builder.Append("Method benchmarked: ");
builder.Append(method.Method.ReflectedType);
builder.Append(".");
builder.AppendLine(method.Method.Name);
builder.Append("Average time in ticks: ");
builder.AppendLine(results.Average(t => t.Ticks).ToString());
return builder.ToString();
}
:
public static void StringConcatOperatorX8()
{
var foo = strings[0] + strings[1] + strings[2] + strings[3] + strings[4] + strings[5] + strings[6] + strings[7] + strings[8];
}
public static void StringBuilderAppendsX8()
{
var builder = new StringBuilder();
builder.Append(strings[0]);
builder.Append(strings[1]);
builder.Append(strings[2]);
builder.Append(strings[3]);
builder.Append(strings[4]);
builder.Append(strings[5]);
builder.Append(strings[6]);
builder.Append(strings[7]);
builder.Append(strings[8]);
var result = builder.ToString();
}
strings - , 9, 30
1 8 concats/appends. , 1 6, 3 10 000 .
UPDATE: (1 , ) . , StringBuilder - . 30 StringBuilder , +... , , , , .
: . + StringBuilder , . , StringBuilder:
public static void StringConcatAltOperatorX8()
{
var foo = strings[0];
foo += strings[1];
foo += strings[2];
foo += strings[3];
foo += strings[4];
foo += strings[5];
foo += strings[6];
foo += strings[7];
foo += strings[8];
}
, 30 1 . , 5.809297 . 12.933227 . StringBuilder 11.27558 . . , .