好吧,我当然可以用一些IndexOf,甚至是Split()来做,但我想我会把它作为一个性能预告片。
我有数据 - 比如100K的这些 - 在LastName,FirstName Mi中我需要将它设为FirstName Mi Lastname。
我认为SubString / IndexOf(',')可以完成这项工作,但希望有一个更优雅/更高效的建议。
有更好的想法吗?
答案 0 :(得分:6)
.Split可能是最快/最简洁的。但是.IndexOf在这种情况下的小测试中是最快的(我们可以依赖两个逗号并使用LastIndexOf)。
将以下代码粘贴到LINQPad以自行测试:
对于10,000,000个结果(最佳指标,因为早期结果可能变化很大),我得到:
Regex Time 00:00:54.1151103
分段时间00:00:21.6187375
IndexOf Time 00:00:24.2403165
我得到1,000,000个结果:
Regex Time 00:00:03.6016272
分段时间00:00:01.5575928
IndexOf Time 00:00:00.9774164
我得到100,000个结果:
Regex Time 00:00:00.2587501
分段时间00:00:00.1013721
IndexOf Time 00:00:00.0980560
void Main()
{
int count = 100000;
WithRegex(count);
WithSplit(count);
WithIndexOf(count);
}
void WithRegex(int count)
{
Regex _commaRegex = new Regex(@",", RegexOptions.Compiled);
string[] names = Enumerable.Range(1,count)
.Select(i => "first,last,middle" + i).ToArray();
List<string> newNames = new List<string>(count);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
foreach (string name in names)
{
string[] split = _commaRegex.Split(name);
StringBuilder sb = new StringBuilder();
sb.Append(split[0]).Append(split[2]).Append(split[1]);
newNames.Add(sb.ToString());
}
stopWatch.Stop();
stopWatch.Elapsed.Dump("Regex Time");
}
void WithSplit(int count)
{
string[] names = Enumerable.Range(1,count)
.Select(i => "first,last,middle" + i).ToArray();
List<string> newNames = new List<string>(count);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
foreach (string name in names)
{
string[] split = name.Split(',');
StringBuilder sb = new StringBuilder();
sb.Append(split[0]).Append(split[2]).Append(split[1]);
newNames.Add(sb.ToString());
}
stopWatch.Stop();
stopWatch.Elapsed.Dump("Split Time");
}
void WithIndexOf(int count)
{
string[] names = Enumerable.Range(1,count)
.Select(i => "first,last,middle" + i).ToArray();
List<string> newNames = new List<string>(count);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
foreach (string name in names)
{
/* This approach only works for 2 commas */
int firstComma = name.IndexOf(',');
int lastComma = name.LastIndexOf(',');
string first = name.Substring(0, firstComma);
string last = name.Substring(firstComma + 1, lastComma-(firstComma+1));
string middle = name.Substring(lastComma + 1);
StringBuilder sb = new StringBuilder();
sb.Append(first).Append(middle).Append(last);
newNames.Add(sb.ToString());
}
stopWatch.Stop();
stopWatch.Elapsed.Dump("IndexOf Time");
}
答案 1 :(得分:3)
但是你这样做,I / O将是这次操作的最佳时间。键入问题可能比实际运行交换程序花费的时间更长。