0

I have the following code in my program: This code will iterate through hundreds of thousands of records and i therefore need to look to see if it can be improved:

private void FillObjectTypes(Type type, ElementMapping mapping )
        {
            foreach (var fieldMapping in mapping.FieldMappings.Values.Where(mpng => mpng.ConversionType == ConversionType.InferFromPropertyType))
            {
                fieldMapping.PropertyType = ReflectionUtils.GetPropertyType(type, fieldMapping.PropertyName);
            }
            mapping.FieldMappingsTypesSet = true;
        }

Any idea to an improvement of the code will be highly appreciated. My main question being how the lambda expression will affect performance.

And the code for the reflection below:

public static Type GetPropertyType(Type objectType, string propertyName)
        {
            CheckCache(objectType);
            try
            {
                return propertiesByType[objectType][propertyName].PropertyType;
            }
            catch(KeyNotFoundException excp)
            {
                throw new KeyNotFoundException($"Failed to find property:'{propertyName}' in object type:'{objectType.Name}'",excp);
            }
        }
Bertrand Paul
  • 97
  • 2
  • 9

2 Answers2

1

Your Lambda expression here is just doing filtering so I cannot think of optimization for this Where clause.

As I have seen some suggestions of using parallel loops I would like to point out that Parallel code is not always faster than the sequential one. And that is because of the extra overhead in creating and synchronizing multiple threads.

I guess that a parallel loop in your example would be slower than a normal sequential one, because the work done in each loop is minimal.

See this and this question

Bakri Bitar
  • 1,543
  • 18
  • 29
0

Use task parallel library to evaluate in parallel

mapping.FieldMappings.Values
    .AsParallel()
    .Where( ... )
    .ForAll( fieldMapping =>
    {
        fieldMapping.PropertyType = ReflectionUntils.GetPropertyType( type, fieldMapping.PropertyName );
    } );
Moho
  • 15,457
  • 1
  • 30
  • 31