DataTable绑定和List<Modle>绑定哪个效率高?
今天我做的三层架构被经理怀疑性能低,他说DataTable从数据库取出来直接绑定到Grid控件里,效率肯定比取出来DataTable然后遍历Row再转换
成实体,再加入List要效率高,其实一开始我也是这么认为的,因为前者只需要一句代码 XXX.DataSource = DataTable. 而后者要写很多,但事实是什么
呢?且看我写的例子。(小弟搞Winform的,html功底比较差,UI粗糙,请见谅)
语言:vb.net
环境: VS2013 预览版 sqlserver 2000
UserTable 表,两个字段,简单测试
1 CREATE TABLE [dbo].[UserTable] ( 2 [ID] [int] NOT NULL , 3 [Name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL 4 ) ON [PRIMARY] 5 GO
这个是时间的测试方法,中间注释的是两个方法,测试的时候,我会只让一个运行
Private Sub TestTime() Dim i As Integer Dim StartTime As DateTime = Now 'DataTable的测试 i = InitByDS() ' List的测试 i = InitByList() Dim EndTime As DateTime = Now Dim RunLength As System.TimeSpan RunLength = EndTime.Subtract(StartTime) Console.WriteLine("花费了" + RunLength.ToString + ": 一共" & i & "条数据") End Sub
DataTable 方式的方法,简单的ADO.net 操作
Private Function InitByDS() As Integer Dim dt As New DataTable Using conn As New SqlConnection(Module1.connString) conn.Open() Using adapter As New SqlDataAdapter("SELECT * FROM UserTable", conn) adapter.Fill(dt) End Using conn.Close() End Using ' 数据绑定 DataGridView1.DataSource = dt Return dt.Rows.Count End Function
List 方式的方法,遍历每行,然后进行实体转换,之后再添加
''' <summary> ''' List方式的方法 ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Private Function InitByList() As Integer Dim dt As New DataTable Using conn As New SqlConnection(Module1.connString) conn.Open() Using adapter As New SqlDataAdapter("SELECT * FROM UserTable", conn) adapter.Fill(dt) End Using conn.Close() End Using Dim list As New List(Of User)(dt.Rows.Count) For Each row As DataRow In dt.Rows list.Add(DataRow2Entitiy(row)) Next DataGridView1.DataSource = list Return list.Count End Function ''' <summary> ''' 行转实体 ''' </summary> Private Function DataRow2Entitiy(row As DataRow) As User Dim user As New User user.ID = row("ID") user.Name = row("Name") Return user End Function ''' <summary> ''' 实体 ''' </summary> ''' <remarks></remarks> Private Class User Public Property ID As Integer Public Property Name As String End Class
然后我进行了三次测试,UserTable 表里的数据我会每次手动加几万条
DataTable 方式 List方式
花费了00:00:00.6109836: 花费了00:00:00.4682583: 一共59400条数据
花费了00:00:01.3130555: 花费了00:00:00.8847060: 一共168300条数据
花费了00:00:02.4116809: 花费了00:00:01.8192686: 一共376200条数据
我简直不敢相信自己的眼睛
暂时还不清楚为啥 DataTable 方式这么的慢,觉得我数据有问题的,可以自己去测试。
哪位大神给解释下