Which is the better way to go and why?
//trivial example
List<string> strings = GetStrings();
foreach (string s in strings)
{
// some operation;
}
strings.ForEach (
delegate(string s)
{
// some operation
}
); 27 79946
Tripper,
I wouldn't say that there is a better way, really, since they pretty
much do the same thing.
The call to ForEach might be a little less performant, because you are
making a call through a delegate (which ultimately is slower than the code
in the braces).
However, I wouldn't say that this is a deal-killer, since LINQ is going
to be heavily based on anonymous delegates doing this kind of thing.
Personally, for something as simple as a foreach, I would just use
foreach, since it is that simple.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Tripper" <Tr*****@discus sions.microsoft .com> wrote in message
news:8E******** *************** ***********@mic rosoft.com... Which is the better way to go and why?
//trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; }
strings.ForEach ( delegate(string s) { // some operation } );
Thanks Nicholas! I wonder then, when is a good time to use List.ForEach over
foreach? Maybe like this?
strings.ForEach (ProcessString) ;
vs.
foreach (s in strings)
{
ProcessString(s );
}
Thanks!
Tripp
"Nicholas Paldino [.NET/C# MVP]" wrote: Tripper,
I wouldn't say that there is a better way, really, since they pretty much do the same thing.
The call to ForEach might be a little less performant, because you are making a call through a delegate (which ultimately is slower than the code in the braces).
However, I wouldn't say that this is a deal-killer, since LINQ is going to be heavily based on anonymous delegates doing this kind of thing.
Personally, for something as simple as a foreach, I would just use foreach, since it is that simple.
Hope this helps.
-- - Nicholas Paldino [.NET/C# MVP] - mv*@spam.guard. caspershouse.co m
"Tripper" <Tr*****@discus sions.microsoft .com> wrote in message news:8E******** *************** ***********@mic rosoft.com... Which is the better way to go and why?
//trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; }
strings.ForEach ( delegate(string s) { // some operation } );
Tripp,
I would say that is a good time, if you want to reduce your code
profile. Then again, the effects are so minimal, I would say it is
inconsequential .
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Tripper" <Tr*****@discus sions.microsoft .com> wrote in message
news:05******** *************** ***********@mic rosoft.com... Thanks Nicholas! I wonder then, when is a good time to use List.ForEach over foreach? Maybe like this?
strings.ForEach (ProcessString) ;
vs.
foreach (s in strings) { ProcessString(s ); }
Thanks!
Tripp
"Nicholas Paldino [.NET/C# MVP]" wrote:
Tripper,
I wouldn't say that there is a better way, really, since they pretty much do the same thing.
The call to ForEach might be a little less performant, because you are making a call through a delegate (which ultimately is slower than the code in the braces).
However, I wouldn't say that this is a deal-killer, since LINQ is going to be heavily based on anonymous delegates doing this kind of thing.
Personally, for something as simple as a foreach, I would just use foreach, since it is that simple.
Hope this helps.
-- - Nicholas Paldino [.NET/C# MVP] - mv*@spam.guard. caspershouse.co m
"Tripper" <Tr*****@discus sions.microsoft .com> wrote in message news:8E******** *************** ***********@mic rosoft.com... > Which is the better way to go and why? > > //trivial example > List<string> strings = GetStrings(); > foreach (string s in strings) > { > // some operation; > } > > strings.ForEach ( > delegate(string s) > { > // some operation > } > );
Hi,
"Tripper" <Tr*****@discus sions.microsoft .com> wrote in message
news:05******** *************** ***********@mic rosoft.com... Thanks Nicholas! I wonder then, when is a good time to use List.ForEach over foreach? Maybe like this?
strings.ForEach (ProcessString) ;
vs.
foreach (s in strings) { ProcessString(s ); }
Thanks!
In my opinion it should perform almost similar, I bet that the
implementation of ForEach is VERY similar to the second code snip, so you
would only be saving in a little typing
Frankly I prefer the second, let's say it's more evident for anybody coming
from any language.
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Tripper wrote: Which is the better way to go and why?
//trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; }
Reflector shows that foreach on a List<string> is not optimized: It
does the full GetEnumerator/while MoveNext.
strings.ForEach ( delegate(string s) { // some operation }
List<T>.ForEach , otoh, does a simple for loop, internal to the List<T>
class.
So, given the example you show, strings.ForEach might actually perform
a bit better: More overhead to call the delegate than to execute an
inline foreach body, but less loop control overhead.
If you were comparing
foreach (string s in strings)
SomeMethod(S);
to
strings.ForEach (SomeMethod);
I'd expect strings.ForEach to come out even farther ahead, although
any differences should be really modest.
Fwiw, I benchmarked "foreach (string s in strings) SomeMethod(S)" vs
"strings.ForEac h(SomeMethod);" with a 7 string list.
10x Inline: 43.58 microseconds.
10x ForEach: 18.72 microseconds.
--
<http://www.midnightbea ch.com>
Tripper <Tr*****@discus sions.microsoft .com> wrote: Which is the better way to go and why?
//trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; }
strings.ForEach ( delegate(string s) { // some operation } );
I was surprised by the results I found when benchmarking, so thought
people might be interested:
using System;
using System.Diagnost ics;
using System.Collecti ons.Generic;
class Test
{
const int Iterations = 10000;
const int Size = 100000;
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
List<string> list = new List<string>();
for (int i=0; i < Size; i++)
{
list.Add("x");
}
{
int sum = 0;
stopwatch.Reset ();
stopwatch.Start ();
for (int i=0; i < Iterations; i++)
{
foreach (string s in list)
{
sum += s.Length;
}
}
TimeSpan t1 = stopwatch.Elaps ed;
Console.WriteLi ne ("First version: {0} (correct? {1})",
t1, sum==Iterations *Size);
}
{
int sum = 0;
stopwatch.Reset ();
stopwatch.Start ();
for (int i=0; i < Iterations; i++)
{
list.ForEach (delegate(strin g s) { sum += s.Length; });
}
TimeSpan t2 = stopwatch.Elaps ed;
Console.WriteLi ne ("Second version: {0} (correct? {1})",
t2, sum==Iterations *Size);
}
{
int sum = 0;
Action<string> action = delegate(string s)
{
sum += s.Length;
};
stopwatch.Reset ();
stopwatch.Start ();
for (int i=0; i < Iterations; i++)
{
list.ForEach (action);
}
TimeSpan t3 = stopwatch.Elaps ed;
Console.WriteLi ne ("Third version: {0} (correct? {1})",
t3, sum==Iterations *Size);
}
}
}
Results:
First version: 00:00:11.509660 8 (correct? True)
Second version: 00:00:05.519300 6 (correct? True)
Third version: 00:00:05.525776 6 (correct? True)
Note that the "sum" variable is different in each case. I don't know
what the performance impact of having a single variable would be, but I
believe there *would* be a difference (primarily or possibly solely to
the first version) due to it being captured by the other delegates.
I'd expected foreach to claim a significant victory...
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jon,
will you blog on this so I can link it from mine?
--
Patrik Löwendahl [C# MVP] http://www.lowendahl.net Tripper <Tr*****@discus sions.microsoft .com> wrote:
Which is the better way to go and why?
//trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; } strings.ForEach ( delegate(string s) { // some operation } ); I was surprised by the results I found when benchmarking, so thought people might be interested:
using System; using System.Diagnost ics; using System.Collecti ons.Generic; class Test { const int Iterations = 10000; const int Size = 100000; static void Main() { Stopwatch stopwatch = new Stopwatch(); List<string> list = new List<string>(); for (int i=0; i < Size; i++) { list.Add("x"); } { int sum = 0; stopwatch.Reset (); stopwatch.Start (); for (int i=0; i < Iterations; i++) { foreach (string s in list) { sum += s.Length; } } TimeSpan t1 = stopwatch.Elaps ed; Console.WriteLi ne ("First version: {0} (correct? {1})", t1, sum==Iterations *Size); } { int sum = 0; stopwatch.Reset (); stopwatch.Start (); for (int i=0; i < Iterations; i++) { list.ForEach (delegate(strin g s) { sum += s.Length; }); } TimeSpan t2 = stopwatch.Elaps ed; Console.WriteLi ne ("Second version: {0} (correct? {1})", t2, sum==Iterations *Size); } { int sum = 0; Action<string> action = delegate(string s) { sum += s.Length; }; stopwatch.Reset (); stopwatch.Start (); for (int i=0; i < Iterations; i++) { list.ForEach (action); } TimeSpan t3 = stopwatch.Elaps ed; Console.WriteLi ne ("Third version: {0} (correct? {1})", t3, sum==Iterations *Size); } } } Results:
First version: 00:00:11.509660 8 (correct? True) Second version: 00:00:05.519300 6 (correct? True) Third version: 00:00:05.525776 6 (correct? True) Note that the "sum" variable is different in each case. I don't know what the performance impact of having a single variable would be, but I believe there *would* be a difference (primarily or possibly solely to the first version) due to it being captured by the other delegates.
I'd expected foreach to claim a significant victory...
Patrik Löwendahl [C# MVP] <pa************ **@home.se> wrote: will you blog on this so I can link it from mine?
Yeah, okay - you talked me into it :) It might not be tonight though.
As an added bonus I'll have the "captured variable" version and another
one where the delegate is a method call.
Tonight's job is continuing with my C# 2.0 pages which I hope to finish
by the end of January. It's not that there'll be reams of stuff on
there, but I don't get a lot of free time these days...
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
| Tripper <Tr*****@discus sions.microsoft .com> wrote:
| > Which is the better way to go and why?
| >
| > //trivial example
| > List<string> strings = GetStrings();
| > foreach (string s in strings)
| > {
| > // some operation;
| > }
| >
| > strings.ForEach (
| > delegate(string s)
| > {
| > // some operation
| > }
| > );
|
| I was surprised by the results I found when benchmarking, so thought
| people might be interested:
|
| using System;
| using System.Diagnost ics;
| using System.Collecti ons.Generic;
|
| class Test
| {
| const int Iterations = 10000;
| const int Size = 100000;
|
| static void Main()
| {
| Stopwatch stopwatch = new Stopwatch();
| List<string> list = new List<string>();
| for (int i=0; i < Size; i++)
| {
| list.Add("x");
| }
|
| {
| int sum = 0;
|
| stopwatch.Reset ();
| stopwatch.Start ();
| for (int i=0; i < Iterations; i++)
| {
| foreach (string s in list)
| {
| sum += s.Length;
| }
| }
| TimeSpan t1 = stopwatch.Elaps ed;
|
| Console.WriteLi ne ("First version: {0} (correct? {1})",
| t1, sum==Iterations *Size);
| }
|
| {
| int sum = 0;
| stopwatch.Reset ();
| stopwatch.Start ();
| for (int i=0; i < Iterations; i++)
| {
| list.ForEach (delegate(strin g s) { sum += s.Length; });
| }
| TimeSpan t2 = stopwatch.Elaps ed;
|
| Console.WriteLi ne ("Second version: {0} (correct? {1})",
| t2, sum==Iterations *Size);
| }
|
| {
| int sum = 0;
|
| Action<string> action = delegate(string s)
| {
| sum += s.Length;
| };
|
| stopwatch.Reset ();
| stopwatch.Start ();
| for (int i=0; i < Iterations; i++)
| {
| list.ForEach (action);
| }
| TimeSpan t3 = stopwatch.Elaps ed;
|
| Console.WriteLi ne ("Third version: {0} (correct? {1})",
| t3, sum==Iterations *Size);
| }
| }
| }
|
| Results:
|
| First version: 00:00:11.509660 8 (correct? True)
| Second version: 00:00:05.519300 6 (correct? True)
| Third version: 00:00:05.525776 6 (correct? True)
|
| Note that the "sum" variable is different in each case. I don't know
| what the performance impact of having a single variable would be, but I
| believe there *would* be a difference (primarily or possibly solely to
| the first version) due to it being captured by the other delegates.
|
| I'd expected foreach to claim a significant victory...
|
|
Just add two lines, and watch the result...
...
stopwatch.Start ();
// Put the list into an array for performance
string[] sa = new string[list.Count]; <----
list.CopyTo(sa, 0); <----
for (int i=0; i != Iterations; i++)
{
foreach (string s in sa)
{
sum += s.Length;
}
}
...
Also, try to run the first two tests only, and watch the results....
Willy. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jeffrey Silverman |
last post by:
Hi, all. I have a linked list. I need an algorithm to create a tree
structure from that list.
Basically, I want to turn this:
$list = array(
array( 'id' => 'A', 'parent_id' => null, 'value' => 'aaa')
, array( 'id' => 'B', 'parent_id' => 'A', 'value' => 'bbb')
, array( 'id' => 'C', 'parent_id' => 'B', 'value' => 'ccc')
, array( 'id' => 'D', 'parent_id' => 'A', 'value' => 'ddd')
|
by: James Curran |
last post by:
I'd like to make the following proposal for a new feature for the C#
language. I have no connection with the C# team at Microsoft. I'm posting
it here to gather input to refine it, in an "open Source" manner, and in an
attempt to build a ground-swell of support to convince the folks at
Microsoft to add it.
Proposal: "first:" "last:" sections in a "foreach" block
The problem:
The foreach statement allows iterating over all the...
|
by: cody |
last post by:
foreach does implicitly cast every object in the collection to the specified
taget type without warning.
Without generics this behaviour had the advantage of less typing for us
since casting was neccessary in nearly every collection. But with generics I
consider this feature of foreach as dangerous. Casting is now almost always
unwanted.
interface IFoo{}
class Foo:IFoo{}
class FooBar:IFoo{}
|
by: garyusenet |
last post by:
I'm a bit confused about the differences of these two commands (what is
the right word for commands here?) when used to enumerate the contents
of an array.
The below example uses both foreach and for to enumerate the contents
of the array.
Also as well as explaining the differences could you explain why the
foreach messagebox isn't working below.
Many TIA.
|
by: =?Utf-8?B?RXZhbiBSZXlub2xkcw==?= |
last post by:
I am a C++ programmer and have been learning C#. I have constructed a List<>
and I want to iterate over it, altering each string in the list.
In C++, I'd just create an iterator and walk the list, so I was looking for
something similar in C#. I looked at foreach, List.ForEach, and IEnumerator.
The problem is that all of them seem to return readonly pointers to the
items in the List. Therefore I can't alter the list. So I'm using a for...
| |
by: =?Utf-8?B?YW1pcg==?= |
last post by:
Hi,
I have a Generic Object that has a private List field item.
I populate the List in a different function
I use a FOREACH LOOP with a FindAll function to get all items that have a
certain match for data in the list and do something to it.
The problem is that it repeats for all data items in the list and not
|
by: Peter Morris |
last post by:
I am not sure what you are asking. You seem to be asking how to implement a
plain IEnumerable on a composite structure, but then your example shows a
flat structure using "yield". Your subject makes me infer that you think
foreach is enirely useless for composite structures.
I will address the subject text, because that makes the most sense to me :-)
Take the following class
public class MyTreeNode : IEnumerable<MyTreeNode>
{
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |