Re: Strange behaviour
- From: <Ged>
- Date: Mon, 3 Sep 2007 14:07:04 +0100
besides the difference between for and foreach the first example will always test each element of the array while the second example only tests until it finds the first non-negative.
Actually, the "i < a.Length && negative" in the loop means it will exit the loop as soon as it finds the first negative.
So, it is does come purely down to the difference between foreach() and for() loops ;-)
Personally, I would use the foreach version, as it is easier to read.
I'm not sure which would be better for performance
HTH
--
Ged Moretta
Senior Software Engineer
AppSense Ltd
www.appsense.com
-----------------------------------------------------------------------
This signature isn't automatic. I have to type it manually every time.
"Christof Nordiek" <cn@xxxxxxxxx> wrote in message news:OcMFxmi7HHA.5096@xxxxxxxxxxxxxxxxxxxxxxx
"Michele" <3rr0r200@xxxxxxxx> schrieb im Newsbeitrag news:op.txxqf4mo30xyjd@xxxxxxxxxxx
In data 31 agosto 2007 alle ore 17:49:28, Stanimir StoyanovOne more question, it's a matter of style:
Which version of AllNegative a good programmer should use?
bool AllNegative(int[] a) {
bool negative = true;
for (int i = 0; i < a.Length && negative; i++)
negative = a[i]<0;
return negative;
}
bool AllNegative(int[] a) {
foreach (int x in a)
if (x>0) return false;
return true;
}
besides the difference between for and foreach the first example will always test each element of the array while the second example only tests until it finds the first non-negative.
This can have a huge performance impact, depending on the content and length of the arrays searched.
This is independant of for/foreach since also a for loop can be exited with return
Christof
.
- References:
- Re: Strange behaviour
- From: Christof Nordiek
- Re: Strange behaviour
- Prev by Date: Re: Strange behaviour
- Next by Date: Re: Get the SQL types from a database
- Previous by thread: Re: Strange behaviour
- Index(es):
Relevant Pages
|