mercredi 19 avril 2017

Comparing properties, which is usually faster Linq Expressions or Reflection/

This method uses Linq expressions to compare two properties of an IWebElement.

public void CompareProperties<T>(
            IEnumerable<IWebElement> twoElements,
            Func<IWebElement, T> firstvalue,
            Func<IWebElement, T> secondvalue,
            Action<string> NotEqual,
            [CallerMemberName] string Caller = "",
            [CallerLineNumber] int line = 0
            )
        {
            var firstPropertyMethod = firstvalue(twoElements.First());
            var secondPropertyMethod = secondvalue(twoElements.Last());
            var paramExpressionA = Expression.Parameter(typeof(T), nameof(firstPropertyMethod));
            var paramExpressionB = Expression.Parameter(typeof(T), nameof(secondvalue));
            var binaryExpression = Expression.Equal(paramExpressionA, paramExpressionB);
            var invokeEqualityOperator = Expression.Lambda<Func<T, T, bool>>(binaryExpression, paramExpressionA, paramExpressionB).Compile();
            var result = invokeEqualityOperator(firstPropertyMethod, secondPropertyMethod);
            if (!result)
            {
                NotEqual(string.Format("Method {0} Line:{1}", Caller, line));
            }
        }

This method does the same thing using Reflection.

  private List<string> CompareAllProperties(IEnumerable<IWebElement> twoElements)
        {
            var fails = new List<string>();
            var propNames = new List<string> { "By", "Displayed", "Enabled", "Location", "Selected", "Size", "TagName", "Text" };
            propNames.ForEach(prop =>
            {
                var firstElement = twoElements.First();
                var lastElement = twoElements.Last();
                var prop1 = GetPropertyValue(firstElement, prop);
                var prop2 = GetPropertyValue(lastElement, prop);
                if (!prop1.Equals(prop2))
                {
                    fails.Add(prop);
                }
            });
            return fails;
        }

Just wondering if one is majorly faster than the other, and your tips on which is better pattern.





Aucun commentaire:

Enregistrer un commentaire