When to use which for?

前端 未结 7 987
慢半拍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:01

    for(int i = 0...) To use this methodology you must have an array that you can access each element of, one by one.

    foreach (SomeClass o in someList) This syntax can be used on an enumerable class, a class that implements IEnumerable. IEnumerable has a method GetEnumerator() that knows how to go through each element of the collection. Now, the array above DOES implement IEnumerable. The way it knows how to enumerate through the collection is how you defined it above. However, not all IEnumerable classes that can use the foreach syntax can use the first method, as not all collections provide access to each element. Consider the following function (didn't test it):

    public IEnumerable GetACoupleOfInts()
    {
    yield return 1;
    yield return 2;
    }
    

    }

    This method will allow you to use the foreach construct, as the runtime knows how to enumerate through the values of GetACoupleInts(), but would not allow the for construct.

    someList.ForEach(o => o.someAction()); - The way I understand it, this lambda will just be converted to the same expression as foreach (SomeClass o in someList)

    someList.AsParallel().ForAll(o => o.someAction()); - When deciding whether or not to use PLINQ you have to decide whether or not the "Juice is worth the squeeze." If the amount of work in someAction() is trivial, then the overhead of the runtime trying to organize all of the data from the concurrent actions will be WAY too much and you would be better off doing it serially.

    tl;dr - The first three will likely result in the same calls and have no real affect on performance, although they have different meanings within the framework. The fourth option needs more consideration before being used.

提交回复
热议问题