Итак, увидев пост Адама Ральфа, я подозревал его решение быть быстрее, чем решение Regex. Просто подумал, что я поделюсь результатами моего тестирования, так как нашел, что это было быстрее.
Есть действительно два фактора в игре (пренебрегая системные переменные): количество подстроки добытых (определяется по количеству разделителей), а общая длина строки. Самый простой сценарий, построенный ниже, использует «A» в качестве подстроки, разделенной двумя пробелами (пробел, за которым следует вкладка). Это подчеркивает влияние количества выделенных подстрок. Я пошел вперед и сделал несколько тестов с переменными, чтобы получить следующие общие уравнения для моей операционной системы.
Regex()
т = (28,33 * + SSL-572) (ПЛА/10^6)
Split(). Где()
т = (6.23 * SSL + 250) (SSN/10^6)
Где t - время выполнения в миллисекундах, SSL - средняя длина подстроки, а SSN - количество подстрок, разделенных строкой.
Эти уравнения можно также записать в виде
т = (28,33 * SL + 572 * ПКР)/10^6
и
т = (6.23 * SL + 250 * ПКР)/10^6
, где SL является общая длина строки (SL = SSL * ПЛА)
Вывод:. разделения() где() быстрее, чем Regex(). Основным фактором является количество подстрок, а длина строки играет второстепенную роль. Производительность составляет около 2x и 5x для соответствующих коэффициентов.
Вот мой код тестирования (вероятно, намного больше материала, чем это необходимо, но это установка для получения нескольких переменных данных о я говорил о)
using System;
using System.Linq;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
public enum TestMethods {regex, split};
[STAThread]
static void Main(string[] args)
{
//Compare TestMethod execution times and output result information
//to the console at runtime and to the clipboard at program finish (so that data is ready to paste into analysis environment)
#region Config_Variables
//Choose test method from TestMethods enumerator (regex or split)
TestMethods TestMethod = TestMethods.split;
//Configure RepetitionString
String RepetitionString = string.Join(" \t", Enumerable.Repeat("A",100));
//Configure initial and maximum count of string repetitions (final count may not equal max)
int RepCountInitial = 100;int RepCountMax = 1000 * 100;
//Step increment to next RepCount (calculated as 20% increase from current value)
Func<int, int> Step = x => (int)Math.Round(x/5.0, 0);
//Execution count used to determine average speed (calculated to adjust down to 1 execution at long execution times)
Func<double, int> ExecutionCount = x => (int)(1 + Math.Round(500.0/(x + 1), 0));
#endregion
#region NonConfig_Variables
string s;
string Results = "";
string ResultInfo;
double ResultTime = 1;
#endregion
for (int RepCount = RepCountInitial; RepCount < RepCountMax; RepCount += Step(RepCount))
{
s = string.Join("", Enumerable.Repeat(RepetitionString, RepCount));
ResultTime = Test(s, ExecutionCount(ResultTime), TestMethod);
ResultInfo = ResultTime.ToString() + "\t" + RepCount.ToString() + "\t" + ExecutionCount(ResultTime).ToString() + "\t" + TestMethod.ToString();
Console.WriteLine(ResultInfo);
Results += ResultInfo + "\r\n";
}
Clipboard.SetText(Results);
}
public static double Test(string s, int iMax, TestMethods Method)
{
switch (Method)
{
case TestMethods.regex:
return Math.Round(RegexRunTime(s, iMax),2);
case TestMethods.split:
return Math.Round(SplitRunTime(s, iMax),2);
default:
return -1;
}
}
private static double RegexRunTime(string s, int iMax)
{
Stopwatch sw = new Stopwatch();
sw.Restart();
for (int i = 0; i < iMax; i++)
{
System.Collections.Generic.IEnumerable<string> ens = Regex.Split(s, @"\s+");
}
sw.Stop();
return Math.Round(sw.ElapsedMilliseconds/(double)iMax, 2);
}
private static double SplitRunTime(string s,int iMax)
{
Stopwatch sw = new Stopwatch();
sw.Restart();
for (int i = 0; i < iMax; i++)
{
System.Collections.Generic.IEnumerable<string> ens = s.Split().Where(x => x != string.Empty);
}
sw.Stop();
return Math.Round(sw.ElapsedMilliseconds/(double)iMax, 2);
}
}
}
См. Также возможный дубликат с SplitStringOptions, чтобы удалить лишние пробелы. http://stackoverflow.com/questions/6111298/best-way-to-specify-whitespace-in-a-string-split-operation – goodeye