+ 2

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; }

11th Apr 2021, 7:51 PM
Ростислав Кравец
Ростислав Кравец - avatar
8 Answers
+ 2
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 :)
11th Apr 2021, 10:33 PM
Schindlabua
Schindlabua - avatar
+ 1
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); } } }
12th Apr 2021, 5:38 PM
BeginEnd
BeginEnd - avatar
0
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.
12th Apr 2021, 1:57 AM
Jerry Hobby
Jerry Hobby - avatar
0
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).
12th Apr 2021, 9:45 PM
Mhd AlHaj Houssein
Mhd AlHaj Houssein - avatar
0
Thanks 😊
23rd May 2021, 8:26 PM
Ростислав Кравец
Ростислав Кравец - avatar
0
I want to know if there is a difference in writing this: for(int i = 0; i < array.Length; i++) { And then using array[i] } Or foreach(datatype oneObject in array) { And then using oneObject } These are for looping objects in an array. Is there a difference and if there is which is better to use. https://www.myloweslife.run/
28th Aug 2021, 8:23 AM
AngusDibbert
- 1
Example?
11th Apr 2021, 7:52 PM
Ростислав Кравец
Ростислав Кравец - avatar
- 1
You are building a Music Player app. You need to implement the MusicPlayer class, which should hold the track names as Strings in an array. The array is already defined in the given code. The player should support the following functions: add: add the given argument track to the tracks array. show: output all track names in the player on separate lines. play: start playing the first track by outputting "Playing name" where name is the first track name. You can add a new item to an array using +=, for example: tracks += track
14th Aug 2021, 12:01 PM
Siyoum Tassew
Siyoum Tassew - avatar