Which is faster? foreach vs. List.ForEach vs. for-loop | SoloLearn: Learn to code for FREE!


Which is faster? foreach vs. List.ForEach vs. for-loop

long Sum(List<int> intList) { long result = 0; intList.ForEach(delegate(int i) { result += i; }); result result; } long Sum(List<int> intList) { long result = 0; foreach (int i in intList) result += i; return result; }

4/11/2021 7:51:05 PM

Ростислав Кравец

7 Answers

New Answer


Run a profiler on your code to find out. It may vary on a case by case basis.


My instinct says it doesn't matter, but we can look at the compiler output: https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyAMABMugCwDcOyAzEagQMIEDeOBbBEA9gHYDmBAZQCuAWwAUAGTABnYAB4w3YAD4Ci4FNkBKZhx78ATgFNpQiMAIBeAnjJqlm4ADoAYpwMBRAIYBjABZiMEYQRrxewEZi6mo6TATGpuYE8NZgdgC+WnbIAOzxJmbAGazsXHyCoqiSMvLqquqOsXrlCYVWNnYAZu5Gvn4EUUpq9vYaNTqtSSlq2XmTRQTpOOlAA=== Switch to IL or ASM mode and look at what your source code ends up as. The first code snippet generates actually two functions, one for Sum and one for the delegate (<Sum>b__0 in the output), so you have to do a function call on each loop pass which would make that snippet slower for sure. (Interesting that this isn't optimized away by the compiler.) However, for completeness: We are talking about nanoseconds here and a "Sum" function will never ever be the bottleneck in your app. Go with whatever looks nicer to you code-wise and what you think is more maintainable. If your app runs poorly this function is probably not the cause :)


Capture the time stamp before and after each scenario. Use a large data sample. Then see how long each method takes to go through a million iterations or whatever.



Class StopWatch can to measure time work program but i not sure what is faster using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; namespace SoloLearn { class Program { static void Main(string[] args) { int result = 0; var lst = new List<int>(); var time = new Stopwatch(); for (int i = 0; i < 25;i++) //Fill list lst.Add(i); time.Start(); lst.ForEach(delegate(int i) { result += i; }); time.Stop(); long time1 = time.ElapsedTicks; time.Restart(); foreach (var item in lst) result += item; time.Stop(); long time2 = time.ElapsedTicks; Console.WriteLine(time1); Console.WriteLine(time2); } } }


In general, (for) loop is faster than (foreach) loop when you use them for iterating on arrays but when using lists, foreach here become a little faster than normal (for). (Collection.ForEach) in the tow previous states is slower than both (for) and (foreach) because it gives you more features can't be done using (foreach) like removing an item from list while iterating on it (in normal foreach this will gives you a runtime error).