@Daniel答案的變體對我來說似乎更加準確。
Guid的長度是36.我們創建一個列表,其中的字符串長度從1到36不等,我們的目標是用方法18取得18,所以大約一半的時間會通過。
我得到的結果表明Take
將是慢6-10倍比Substring
。
結果例子:
Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms
Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms
所以,對於5000000串,做大致2.5百萬計的操作,總時間爲2.1秒,或周圍0.0008564毫秒=〜1微秒每次操作。如果你覺得你需要爲子串削減5,那就去做吧,但是我懷疑現實生活中的情況,除了緊身衣循環之外,你會感受到它們之間的差異。
void Main()
{
Console.WriteLine("Build time: {0} ms", BuildInput());
Console.WriteLine("Time substring: {0} ms, Time take: {1} ms", MeasureSubstring(), MeasureTake());
}
internal const int RETRIES = 5000000;
static internal List<string> input;
// Measure substring time
private static long MeasureSubstring()
{
var v = new List<string>();
long ini = Environment.TickCount;
foreach (string test in input)
if (test.Length > 18)
{
v.Add(test.Substring(18));
}
//v.Count().Dump("entries with substring");
//v.Take(5).Dump("entries with Sub");
return Environment.TickCount - ini;
}
// Measure take time
private static long MeasureTake()
{
var v = new List<string>();
long ini = Environment.TickCount;
foreach (string test in input)
if (test.Length > 18) v.Add(new string(test.Take(18).ToArray()));
//v.Count().Dump("entries with Take");
//v.Take(5).Dump("entries with Take");
return Environment.TickCount - ini;
}
// Create a list with random strings with random lengths
private static long BuildInput()
{
long ini = Environment.TickCount;
Random r = new Random();
input = new List<string>();
for (int i = 0; i < RETRIES; i++)
input.Add(Guid.NewGuid().ToString().Substring(1,r.Next(0,36)));
return Environment.TickCount - ini;
}
使用秒錶執行計時。此外,你可以編寫自己的擴展方法來進行檢查。 – 2013-03-14 10:01:23
我會說,採取將枚舉你的字符串。這可能會對長字符串產生巨大影響。 – jbl 2013-03-14 10:03:16
性能是sooooo上下文的。 – crypted 2013-03-14 10:46:08