Looking under the hood

Because of some people I've met in my career, I have the importunity of looking under the hood when

Because of some people I've met in my career, I have the importunity of looking under the hood when using method e.g. from FCL. It's one of the best things you can learn and adapt - always make sure you have at least a small idea what's going on behind the scenes.

Recently I've been playing with Parallel.ForEach so I went through the code. The very first call looks like this:

Parallel.ForEach() -> ForEachWorker<TSource, object>()

There's nothing fancy going here. But let's go deeper and investigate ForEachWorker<TSource, object>() method:
// If it's an array, we can use a fast-path that uses ldelems in the IL.
TSource[] sourceAsArray = source as TSource[]; 
if (sourceAsArray != null)
{ 
      return ForEachWorker<TSource, TLocal>( 
         sourceAsArray, parallelOptions, body, bodyWithState, bodyWithStateAndIndex, bodyWithStateAndLocal,
         bodyWithEverything, localInit, localFinally); 
}

// If we can index into the list, we can use a faster code-path that doesn't result in
// contention for the single, shared enumerator object. 
IList<TSource> sourceAsList = source as IList<TSource>;
if (sourceAsList != null) 
{ 
     return ForEachWorker<TSource, TLocal>(
        sourceAsList, parallelOptions, body, bodyWithState, bodyWithStateAndIndex, bodyWithStateAndLocal, 
        bodyWithEverything, localInit, localFinally);
}

// This is an honest-to-goodness IEnumerable.  Wrap it in a Partitioner and defer to our 
// ForEach(Partitioner) logic.
return PartitionerForEachWorker<TSource, TLocal>(Partitioner.Create(source), parallelOptions, body, bodyWithState, 
        bodyWithStateAndIndex, bodyWithStateAndLocal, bodyWithEverything, localInit, localFinally); 
because this part is really well documented, you can clearly see what steps were taken to improve performance of this method. By knowing this you can adjust your code to make sure, you're using it in the most efficient way.
 
I strongly encourage you to always read source code of libraries you're using, so you can understand all gotchas and implementation details. In less than a minute you can find something, what will help you in making your code better and faster.

Add comment