What implementation of cycle is better?
I wonder, what implementation is better from reading and performance sides.
1)for (DateTime
dayStart = GetDayStart(today),
dayEnd = GetDayEnd(today);
dayStart < endOfPeriod;
dayStart = dayStart.AddDays(1), dayEnd = dayEnd.AddDays(1))
{
// ...
}
2)
DateTime dayStart = GetDayStart(today),
dayEnd开发者_高级运维 = GetDayEnd(today);
while (dayStart < endOfPeriod)
{
// ...
dayStart = dayStart.AddDays(1);
dayEnd = dayEnd.AddDays(1);
}
3) Or, may be any another?
Thanks in advance.
For readability I would go with the second choise. The for
statement is great for simpler loops, but it gets harder to follow when it gets more complicated.
For performance there should be no difference at all. The compiler will likely produce the exact same code from the two different source codes.
Personally, I find the second one the most readable. Multiple statements in a for-loop are more error-prone and less clear to an objective reader of your code.
If you looking for minor variations of your approach you could also look at using Timespan...
DateTime dayStart = GetDayStart(today);
TimeSpan days = GetDayEnd(today) - dayStart;
while (dayStart < endOfPeriod)
{
DateTime dayEnd = dayStart.Add(days);
// ...
dayStart = dayStart.AddDays(1);
}
Only reason I like this more is because I didn't like the fact you had to increment both dates.
精彩评论