jeudi 26 juillet 2018

C# - Ways to improve this code

I have written a method which simply copies all given properties of a objects to an other with the same type. This method is made because I don't want to manually define the properties to copy when a class has 100+ (hope this never happens, but if...).

    /// <summary>
    /// Copies the values of the given parameters from source to target
    /// Important Info: Works only with Properties, not with Fields
    /// </summary>
    /// <typeparam name="T">The Classtype</typeparam>
    /// <param name="target">The object the values are copied to</param>
    /// <param name="source">The object the values come from</param>
    /// <param name="properties">The Array containing the names of properties which shall be copied</param>
    private static void CopyParams<T>(T target, T source, params string[] properties)
    {
        foreach (var property in properties)
        {
            target.GetType().GetProperty(property)?.SetValue(target, source.GetType().GetProperty(property)?.GetValue(source));
        }
    }

But because this uses reflection inside a loop, this is extremly slow. With 1.000.000 objects and 2 properties, it takes up to 2 seconds. If I do this manually, it takes 36 ms. Is there a way to improve this in performance?





Aucun commentaire:

Enregistrer un commentaire