Declaring a variable inside or outside an foreach loop: which is faster/better?

前端 未结 10 1776
灰色年华
灰色年华 2020-11-27 14:58

Which one of these is the faster/better one?

This one:

List list = new List();
User u;

foreach (string s in l)
{
    u = new         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 15:35

    Whenever you've a question about performance, the only thing to do is measure - run a loop around your test and time it.

    To answer your question - without measuring :-) or looking at the generated ilasm - any difference wouldn't be noticeable in a meaningful number of iterations and the most expensive operation in your code there is likely to be the user allocation by a few orders of magnitude, so concentrate on code clarity (as you should in general) and go with 2.

    Oh, its late and I guess I'm just trying to say don't worry about this sort of thing or get caught up in details like this.

    K

提交回复
热议问题