I wrote a small program to test the speed of two separate extension methods I created, detailed in the below screenshot:
public static class Extensions
{
public static List<string> ParseEmails(this string[] emails, char[] charsToSplitOn)
{
List<string> list = new List<string>();
foreach (string email in emails)
{
string[] splitArr = email.Replace(" ", "").Split(charsToSplitOn, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in splitArr)
{
list.Add(item);
}
}
return list;
}
public static string[] ParseEmails2(this string[] emails, char[] charsToSplitOn)
{
string str = string.Empty;
foreach (string item in emails)
{
str += item + ';';
}
return str.Replace(" ", "").Split(charsToSplitOn, StringSplitOptions.RemoveEmptyEntries);
}
}
The Main method initializes a Stopwatch
class to track the time each method takes to execute iterations
amount of times.
The first method, ParseEmails
has a for
loop within another for
loop, while the second method 'ParseEmails2' has only one for
loop.
I would expect that then the second method, ParseEmails2
, would be faster, as, from my understanding, this is done in O(n) time, whereas my first method, ParseEmails
, is done in O(n^2) time.
If this is true, then shouldn't my results point to ParseEmails2
being the faster of the two methods?