When to use which for?

前端 未结 7 928
慢半拍i
慢半拍i 2021-01-05 14:48

EDIT Additional options and a slightly extended question below.

Consider this contrived and abstract example of a class body. It demonstrates four different w

7条回答
  •  太阳男子
    2021-01-05 15:02

    As far as performance is concerned I think one of these would work best.

      //A. for
        for (int i = 0; i < someList.Count(); i++)
        {
            someList[i].someAction();
        }
    

    or

     //D. plinq
        someList.AsParallel().ForAll(o => o.someAction());
    

    Although in case of A, I would prefer not to do someList.Count() every time.

    for performs better as compared to foreach as far as performance is concerned. D can be better than A but it would depend on the scenario. If you have some large data in somelist, Parallelism might help but if you have small data, it can cause extra burden

提交回复
热议问题