collection.Where(i => i.condition)
.ToList()
.ForEach(i => SomeComplicatedOpInvolving_i);
I'm not looking for answers telling me there is an easier way of doing this, just treat it as a thought experiment.
First up, am I right in thinking that this is three loops? Where()
, ToList()
and ForEach()
?
Second of all, (assuming it is three loops) am I right in thinking this is n to the power of 3 in big O notation?
Thanks everyone.
To your other question, the answer is no. They aren't always O(n^2) . You can easily create a situation where one of the loops affects the iterations of the other, yielding a different complexity.
It would be O(2n) because you run n+n = 2n iterations. O(2n) is essentially equivalent to O(n) as 2 is a constant.
No, actually. I think it should be O(n).
Where()
runs in O(n) (assuming condition
is constant)
ToList()
runs over all the results of Where
as well, so O(n) too
ForEach()
runs over the entire list produced by ToList
once, so also O(n). I assume SomeComplicatedOpInvolving_i
doesn't scale with the number of i's...
The key point here is that the loops aren't nested, they run one after another - so total runtime is 3*O(n), which is the same as O(n).
No, they are not nested loops. It is O(n).
Avoid using ToList(), that costs O(n) storage for no good reason. Check this blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With