stringbuild的拼接快不快_String.Join vs. StringBuilder:哪个更快?

这是我的试验台,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();

}

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值