namespace GetDataTest { public class SqlDirect { private static void GetDataBindExtracted(out SqlDataReader reader) { reader = SqlHelper.ExecuteReader(SqlConfigHelper.SqlContext(), CommandType.Text, "select Id,TestValue from dbo.Test", null); } /// <summary> /// 直接读取(强类型转换) /// </summary> public static TimeSpan GetDataBindOnParse() { List<TextCode> list = new List<TextCode>(); ; SqlDataReader reader; GetDataBindExtracted(out reader); Stopwatch watch = new Stopwatch(); watch.Start(); if (reader.HasRows) { while (reader.Read()) { TextCode code = new TextCode { Id = Guid.Parse(reader["Id"].ToString()), TestValue = DateTime.Parse(reader["TestValue"].ToString()) }; list.Add(code); } } return watch.Elapsed; } /// <summary> /// 直接读取(拆箱) /// </summary> /// <returns></returns> public static TimeSpan GetDataBindOnUnbox() { List<TextCode> list = new List<TextCode>(); ; SqlDataReader reader; GetDataBindExtracted(out reader); Stopwatch watch = new Stopwatch(); watch.Start(); if (reader.HasRows) { while (reader.Read()) { TextCode code = new TextCode { Id = (Guid)reader["Id"], TestValue = (DateTime)reader["TestValue"] }; list.Add(code); } } return watch.Elapsed; } /// <summary> /// 反射方式读取 /// </summary> public static TimeSpan GetDataBindOnRef<T>() where T:class,new() { List<T> list = new List<T>(); ; SqlDataReader reader; GetDataBindExtracted(out reader); Stopwatch watch = new Stopwatch(); watch.Start(); while (reader.Read()) { T entity = new T(); for (int i = 0; i < reader.FieldCount; i++) { PropertyInfo proinfo = entity.GetType().GetProperty(reader.GetName(i)); proinfo.SetValue(entity, reader.GetValue(i), null); } list.Add(entity); } return watch.Elapsed; } } }
不是说直接读取比反射效率高么?这当中原因不太懂,是应为强类型转换拉低了效率么,拆箱的效率很高么?还是应为是引用类型的问题?还是我的测试方式不对,为什么结果和之前在书上或别人说的不一样呢,我凌乱了...
Id = Guid.Parse(reader["Id"].ToString()), TestValue = DateTime.Parse(reader["TestValue"].ToString()) };两次类型转换降低了效率 3Q钱锅
'直接读取比反射效率高' 也要看情况啊, 你这边(拆箱)不是比反射快嘛! 你写的强制转换比拆箱慢了8倍...不想想原因啊..