How slow is Reflection

后端 未结 7 2033
时光取名叫无心
时光取名叫无心 2020-12-02 07:43

I recently created an interface layer to distinguish the DataAccessProvider from our Business logic layer. With this approach we can change our choice of DataAccessProvider

7条回答
  •  天命终不由人
    2020-12-02 07:56

    I thought I'd do a quick test to demonstrate how slow reflection is compared to without.

    With Reflection

    • Instantiating 58 objects by iterating through each of their Attributes and matching
    • Total Time: 52254 nanoseconds

      while (reader.Read()) {
          string[] columns = reader.CurrentRecord;
          CdsRawPayfileEntry toAdd = new CdsRawPayfileEntry();
          IEnumerable rawPayFileAttributes = typeof(CdsRawPayfileEntry).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(CustomIndexAttribute)));
          foreach (var property in rawPayFileAttributes) {
              int propertyIndex = ((CustomIndexAttribute)property.GetCustomAttribute(typeof(CustomIndexAttribute))).Index;
              if (propertyIndex < columns.Length)
                  property.SetValue(toReturn, columns[propertyIndex]);
              else
                  break;
          }
      }
      

    Without Reflection

    • Instantiating 58 Objects by creating a new object
    • Total Time: 868 nanoseconds

          while (reader2.Read()) {
              string[] columns = reader2.CurrentRecord;
              CdsRawPayfileEntry toAdd = new CdsRawPayfileEntry() {
                  ColumnZero = columns[0],
                  ColumnOne = columns[1],
                  ColumnTwo = columns[2],
                  ColumnThree = columns[3],
                  ColumnFour = columns[4],
                  ColumnFive = columns[5],
                  ColumnSix = columns[6],
                  ColumnSeven = columns[7],
                  ColumnEight = columns[8],
                  ColumnNine = columns[9],
                  ColumnTen = columns[10],
                  ColumnEleven = columns[11],
                  ColumnTwelve = columns[12],
                  ColumnThirteen = columns[13],
                  ColumnFourteen = columns[14],
                  ColumnFifteen = columns[15],
                  ColumnSixteen = columns[16],
                  ColumnSeventeen = columns[17]
              };
          }
      

    Albeit, not completely fair since the reflection also has to retrieve a specific attribute of every property 58*18 times on top of creating a new object via reflection, but it at least provides some perspective.

提交回复
热议问题