What is the major difference between for
and foreach
loops?
In which scenarios can we use for
and not foreach
and vice versa.
Would it be possible to show with a simple program?
Both seem the same to me. I can't differentiate them.
foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items. The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
a for
loop is a construct that says "perform this operation n. times".
a foreach
loop is a construct that says "perform this operation against each value/object in this IEnumerable"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With