@Daniel 答案的变体对我来说似乎更准确。
Guid 的长度是 36。我们正在创建一个列表,其中包含从 1 到 36 的可变长度字符串,我们的目标是使用substring
/take
方法获取 18,所以大约一半会通过。
我得到的结果表明这Take
将比. 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
因此,对于500 万个字符串,大约执行250 万次操作,总时间为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;
}