A variation of @Daniel answer that seems more accurate to me.
a Guid's length is 36. We're creating a list with a variable length of strings from 1 to 36, and we'll aim for taking 18 with the substring
/ take
methods, so around half will go through.
The results I'm getting suggest that Take
will be 6-10 times slower than Substring
.
Results example :
Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms
Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms
so, for 5 million strings, doing roughly 2.5 millions operations, total time is 2.1 seconds , or around 0.0008564 milliseconds = ~ 1 micro second per operation. If you feel you need to cut it by 5 for substring, go for it, but I doubt in real life situations, outside of tights loop, you'll ever feel the difference.
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;
}