Edward
Edward

Reputation: 896

Code performance on double for loop compare to linq/lambda

I like the look of linq/lambda statement and wonder about the performance of this

var temp = list1.ForEach(x => list2.ForEach(y => Tuple.Create(y[1]+" "+y[2]+" "+x[0]+" "+x[1]) );

compared to this:

foreach(var x in list1)
  foreach(var y in list2)
    var temp = Tuple.Create(y[1]+" "+y[2]+" "+x[0]+" "+x[1]);

Still not familiar with how people describe performance in terms of O(nlogn) but from constant interaction with this type of chat I understand the double loop gives usually O(n^2)

Upvotes: 0

Views: 131

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Both statements are equal on their complexity, namely O(n^2). Internally the ForEach-statement will create a simply loop doing what is determined by the lambda-statement. So the total number of calls to the inner code is the same making both approaches similar in their complexity.

Anyway to get meaningful results on your actual time-performance you should use some profiling-tools, e.g. Resharper. Alternatively simply add some Stopwatch statements into your code to measure how long things need to proceed.

Upvotes: 3

B.Rickman
B.Rickman

Reputation: 71

When the compiler turns these into machine readable code, both are doing the same function. This specific case is just a nested loop either way. Both should be O(n^2) i believe and its a matter of what you think looks better in this case. because you have list1.foreach, then inside list2.foreach its the same as writing

foreach()
{
    foreach()
    {
    }
}

Upvotes: 1

Related Questions