性能差异c#foreach for linq

Dan*_*ico 1 .net c# linq performance foreach

我想知道这是区别:

对于:

string[] arrayOld = new string(){"This", "other", "aaa", ...};
string[] arrayNew = new string[arrayOld.lenght];

for(int i = i < arrayOld.lenght; i++){
   arrayNew[i] = arrayOld[i];
}
Run Code Online (Sandbox Code Playgroud)

FOREACH:

string[] arrayOld = new string(){"This", "other", "aaa", ...};
List<string> listNew = new List<string>();

foreach(string val in arrayOld){
   listNew.add(val);
}
string[] arrayNew = listNew.toArray();
Run Code Online (Sandbox Code Playgroud)

LINQ:

string[] arrayOld = new string(){"This", "other", "aaa", ...};
string[] arrayNew = (from val in arrayOld select val).toArray();
Run Code Online (Sandbox Code Playgroud)

我不想复制数组......

这个想法是从arrayOld中的对象构造新对象(可以与string不同,可以包含其他属性......)

我需要表现,所以...

¿什么是最好的选择,为什么?

Jus*_*ner 10

以上都不是.

如果您正在尝试复制数组,我会尝试:

string[] arrayOld = new { "This", "other", "aaa" };
string[] arrayNew = new string[arrayOld.Length];

arrayOld.CopyTo(arrayNew, 0);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 10

原油结果最适合自己:

class Program
{
    static void Main()
    {
        // Warm-up
        Method1();
        Method2();
        Method3();

        const int Count = 1000000;

        var watch = Stopwatch.StartNew();
        for (int i = 0; i < Count; i++)
        {
            Method1();
        }
        watch.Stop();
        Console.WriteLine("Method1: {0} ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < Count; i++)
        {
            Method2();
        }
        watch.Stop();
        Console.WriteLine("Method2: {0} ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < Count; i++)
        {
            Method3();
        }
        watch.Stop();
        Console.WriteLine("Method3: {0} ms", watch.ElapsedMilliseconds);

    }

    static void Method1()
    {
        string[] arrayOld = new[] { "This", "other", "aaa" };
        string[] arrayNew = new string[arrayOld.Length];

        for (var i = 0; i < arrayOld.Length; i++)
        {
            arrayNew[i] = arrayOld[i];
        }
    }

    static void Method2()
    {
        string[] arrayOld = new[] { "This", "other", "aaa" }; 
        var listNew = new List<string>(arrayOld.Length);

        foreach(var val in arrayOld)
        { 
            listNew.Add(val); 
        } 
        string[] arrayNew = listNew.ToArray();    
    }

    static void Method3()
    {
        string[] arrayOld = new[] { "This", "other", "aaa" }; 
        string[] arrayNew = (from val in arrayOld select val).ToArray();    
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上打印:

Method1: 72 ms
Method2: 187 ms
Method3: 377 ms
Run Code Online (Sandbox Code Playgroud)