这是我的试验台,int[][]用于简单; 结果第一:Join: 9420ms (chk: 210710000OneBuilder: 9021ms (chk: 210710000
(更新double结果:)Join: 11635ms (chk: 210710000OneBuilder: 11385ms (chk: 210710000
(更新re 2048 * 64 * 150)Join: 11620ms (chk: 206409600OneBuilder: 11132ms (chk: 206409600
并启用OptimizeForTesting:Join: 11180ms (chk: 206409600OneBuilder: 10784ms (chk: 206409600
如此之快,但不是那么大; rig(在控制台上运行,在发布模式下运行等):using System;using System.Collections.Generic;using System.Diagnostics;using System.Text;namespace ConsoleApplication2{
class Program
{
static void Collect()
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
}
static void Main(string[] args)
{
const int ROWS = 500, COLS = 20, LOOPS = 2000;
int[][] data = new int[ROWS][];
Random rand = new Random(123456);
for (int row = 0; row
{
int[] cells = new int[COLS];
for (int col = 0; col
{
cells[col] = rand.Next();
}
data[row] = cells;
}
Collect();
int chksum = 0;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i
{
chksum += Join(data).Length;
}
watch.Stop();
Console.WriteLine("Join: {0}ms (chk: {1}", watch.ElapsedMilliseconds, chksum);
Collect();
chksum = 0;
watch = Stopwatch.StartNew();
for (int i = 0; i
{
chksum += OneBuilder(data).Length;
}
watch.Stop();
Console.WriteLine("OneBuilder: {0}ms (chk: {1}", watch.ElapsedMilliseconds, chksum);
Console.WriteLine("done");
Console.ReadLine();
}
public static string Join(int[][] array)
{
return String.Join(Environment.NewLine,
Array.ConvertAll(array,
row => String.Join(",",
Array.ConvertAll(row, x => x.ToString()))));
}
public static string OneBuilder(IEnumerable source)
{
StringBuilder sb = new StringBuilder();
bool firstRow = true;
foreach (var row in source)
{
if (firstRow)
{
firstRow = false;
}
else
{
sb.AppendLine();
}
if (row.Length > 0)
{
sb.Append(row[0]);
for (int i = 1; i
{
sb.Append(',').Append(row[i]);
}
}
}
return sb.ToString();
}
}}