开发者

what is difference between foreach and delegate loop in c#

I have read here http://bytes.com/topic/c-sharp/answers/447223-foreach-list-foreach that someone tell th开发者_运维百科at delegate loop is less performance then foreach commands.

Well i want to know what is difference between both. why foreach better and in which case we only need to use delegate looping.

Is there anyone who has compared both things.


You can implement those two solution and then compare them in IL.

Then you will know that is there some significant difference.

Regarding the performance write two apps, with some time diagnostic create a loop with 1mln entries and execute. Then at the end compare the execution time.

EDIT:

The difference might be in usage, using delegate you can perform operation on example string list by an uknow method

delegate StringListOperator(string s)

public operate(StringListOperator operator) {
   String.ForEach(operator);
}

I'n not 100% sure about syntax but i hope you got the point.

If You only plan to iterate through list in some method IMHO use simple foreach, this look like only a syntax sugar for me.


Take a look at that link: http://www.eggheadcafe.com/software/aspnet/33593372/delegate-vs-foreach-loop.aspx In the question is your question and in the comments there are pretty good answers.


Performance typically won't be a problem however you have to be careful of state capture when using the delegate vs the foreach loop. Basically the compiler will copy variables used inside the loop that are not constants into a nested set of fields. This can at times call undesirable effects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜