C# - 交换最后,第一个MI最快的方式

Lar*_*yR 1 c# string

好吧,我当然可以使用一些IndexOf,甚至是Split(),但我想我会把它作为一个性能预告片.

我有数据 - 比如100K的这些 - 在LastName,FirstName Mi中我需要将它设为FirstName Mi Lastname.

我认为SubString/IndexOf(',')可以完成这项工作,但希望有一个更优雅/高性能的建议.

有更好的想法吗?

Mat*_*ell 6

.Split可能是最快/最简洁的.然而.IndexOf在这种情况下的小测试中出乎意料地最快(我们可以依赖两个逗号并使用LastIndexOf).

将以下代码粘贴到LINQPad中自行测试:

对于10,000,000个结果(最佳指标,因为早期结果可能变化很大),我得到:

正则表达式时间00:00:54.1151103

分段时间00:00:21.6187375

IndexOf时间00:00:24.2403165

我得到1,000,000个结果:

正则表达式时间00:00:03.6016272

分段时间00:00:01.5575928

IndexOf时间00:00:00.9774164

我得到100,000个结果:

正则表达式时间00:00:00.2587501

分段时间00:00:00.1013721

IndexOf时间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");  
}  
Run Code Online (Sandbox Code Playgroud)

  • 出于计时目的,请使用"秒表",而不是"DateTime.Now". (2认同)