优化代码以减少反射对性能的影响

时间:2018-09-22 19:51:00

标签: reflection .net-core

我正在基于.Net Core和ADO.Net构建Web API

我使用以下代码从DataRow中填充模型对象:

public IEnumerable<TEntity> Map(DataTable table)
    {
        List<TEntity> entities = new List<TEntity>();
        var columnNames = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
        var properties = (typeof(TEntity)).GetProperties().ToList();

        foreach (DataRow row in table.Rows)
        {
            TEntity entity = new TEntity();
            foreach (var prop in properties)
            {
                PropertyMapHelper.Map(typeof(TEntity), row, prop, entity);
            }
            entities.Add(entity);
        }

        return entities;
    }

并使用此其他代码创建必要的SQL Update命令:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
    {
        var properties = (typeof(TEntity)).GetProperties().ToList();
        string sProps = "";
        string sCommand = "";

        foreach (var prop in properties)
        {                
            bool bIgnore = prop.GetCustomAttributes(true).Any(a => a is KeyAttribute);
            if (prop.Name.ToUpper() != sKeyField.ToUpper() && !bIgnore)
            {
                sProps = sProps + prop.Name + "=@" + prop.Name + ", ";

                var p = myCommand.CreateParameter();
                p.ParameterName = prop.Name;
                if (prop.GetValue(entity) == null)
                    p.Value = DBNull.Value;
                else
                    p.Value = prop.GetValue(entity);

                myCommand.Parameters.Add(p);
            }
        }
        sProps = sProps.Substring(0, sProps.Length - 2);

        sCommand = "UPDATE [" + sTable + "] SET " + sProps;
        sCommand = sCommand + " WHERE " + sWhere;

        myCommand.CommandText = sCommand;
    }

我知道反射会影响性能,因此我正在寻找有关如何改进此代码的建议。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以考虑使用Dapper。它是ADO.NET的包装,因此从技术上讲它不能比ADO.NET快,但是与通过ADO.NET处理数据的自定义代码相比,在大多数情况下,它使用更好的编码方法,因此可能会给the better performance results