據庫中使用自增量字段與Guid字段主鍵的性能對比
1.概述:
在我們的數據庫設計中,數據庫的主鍵是必不可少的,主鍵的設計對整個數據庫的設計影響很大.我就對自動增量字段與Guid字段的性能作一下對比,歡迎大家討論.
2.簡介:
1.自增量字段
自增量字段每次都會按順序遞增,可以保證在一個表里的主鍵不重復。除非超出了自增字段類型的最大值并從頭遞增,但這幾乎不可能。使用自增量字段來做主鍵是非常簡單的,一般只需在建表時聲明自增屬性即可。
自增量的值都是需要在系統中維護一個全局的數據值,每次插入數據時即對此次值進行增量取值。當在當量產生唯一標識的并發環境中,每次的增量取值都必須最此全局值加鎖解鎖以保證增量的唯一性。這可能是一個并發的瓶頸,會牽扯一些性能問題。
在數據庫遷移或者導入數據的時候自增量字段有可能會出現重復,這無疑是一場惡夢(本人已經深受其害).
如果要搞分布式數據庫的話,這自增量字段就有問題了。因為,在分布式數據庫中,不同數據庫的同名的表可能需要進行同步復制。一個數據庫表的自增量值,就很可能與另一數據庫相同表的自增量值重復了。
2.uniqueidentifier(Guid)字段
在MS Sql 數據庫中可以在建立表結構是指定字段類型為uniqueidentifier,并且其默認值可以使用NewID()來生成唯一的Guid(全局唯一標識符).使用NewID生成的比較隨機,如果是SQL 2005可以使用NewSequentialid()來順序生成,在此為了兼顧使用SQL 2000使用了NewID().
Guid:指在一臺機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,其算法是通過以太網卡地址、納秒級時間、芯片ID碼和許多可能的數字生成。其格式為:04755396-9A29-4B8C-A38D-00042C1B9028.
Guid的優點就是生成的id比較唯一,不管是導出數據還是做分步開發都不會出現問題.然而它生成的id比較長,占用的數據庫空間也比較多,隨著外存價格的下降,這個也無需考慮.另外Guid不便于記憶,在這方面不如自動增量字段,在作調試程序的時候不太方便。
3.測試:
1.測試環境
操作系統:windows server 2003 R2 Enterprise Edition Service Pack 2
數據庫:MS SQL 2005
CPU:Intel(R) Pentium(R) 4 CPU 3.40GHz
內存:DDRⅡ 667 1G
硬盤:WD 80G
2.數據庫腳本
--自增量字段表
CREATE TABLE [dbo].[Table_Id](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Value] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_Table_Id] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
--Guid字段表
CREATE TABLE [dbo].[Table_Guid](
[Guid] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Table_Guid_Guid] DEFAULT (newid()),
[Value] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_Table_Guid] PRIMARY KEY CLUSTERED
(
[Guid] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
測試代碼
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Data.SqlClient;
5
using System.Diagnostics;
6
using System.Data;
7
8
namespace GuidTest
9

{
10
class Program
11
{
12
string Connnection = "server=.;database=GuidTest;Integrated Security=true;";
13
static void Main(string[] args)
14
{
15
Program app = new Program();
16
int Count = 10000;
17
Console.WriteLine("數據記錄數為{0}",Count);
18
//自動id增長測試;
19
Stopwatch WatchId = new Stopwatch();
20
Console.WriteLine("自動增長id測試");
21
Console.WriteLine("開始測試");
22
WatchId.Start();
23
Console.WriteLine("測試中
");
24
25
app.Id_InsertTest(Count);
26
//app.Id_ReadToTable(Count);
27
//app.Id_Count();
28
29
//查詢第300000條記錄;
30
//app.Id_SelectById();
31
32
WatchId.Stop();
33
Console.WriteLine("時間為{0}毫秒",WatchId.ElapsedMilliseconds);
34
Console.WriteLine("測試結束");
35
36
Console.WriteLine("-----------------------------------------");
37
//Guid測試;
38
Console.WriteLine("Guid測試");
39
Stopwatch WatchGuid = new Stopwatch();
40
Console.WriteLine("開始測試");
41
WatchGuid.Start();
42
Console.WriteLine("測試中
");
43
44
app.Guid_InsertTest(Count);
45
//app.Guid_ReadToTable(Count);
46
//app.Guid_Count();
47
48
//查詢第300000條記錄;
49
//app.Guid_SelectById();
50
51
WatchGuid.Stop();
52
Console.WriteLine("時間為{0}毫秒", WatchGuid.ElapsedMilliseconds);
53
Console.WriteLine("測試結束");
54
Console.Read();
55
}
56
57
/**////
58
/// 自動增長id測試
59
///
60
private void Id_InsertTest(int count)
61
{
62
string InsertSql="insert into Table_Id ([Value]) values ({0})";
63
using (SqlConnection conn = new SqlConnection(Connnection))
64
{
65
conn.Open();
66
SqlCommand com = new SqlCommand();
67
for (int i = 0; i < count; i++)
68
{
69
com.Connection = conn;
70
com.CommandText = string.Format(InsertSql, i);
71
com.ExecuteNonQuery();
72
}
73
}
74
}
75
76
/**////
77
/// 將數據讀到Table
78
///
79
private void Id_ReadToTable(int count)
80
{
81
string ReadSql = "select top " + count.ToString() + " * from Table_Id";
82
using (SqlConnection conn = new SqlConnection(Connnection))
83
{
84
SqlCommand com = new SqlCommand(ReadSql, conn);
85
SqlDataAdapter adapter = new SqlDataAdapter(com);
86
DataSet ds = new DataSet();
87
adapter.Fill(ds);
88
Console.WriteLine("數據記錄數為:{0}", ds.Tables[0].Rows.Count);
89
}
90
}
91
92
/**////
93
/// 數據記錄行數測試
94
///
95
private void Id_Count()
96
{
97
string ReadSql = "select Count(*) from Table_Id";
98
using (SqlConnection conn = new SqlConnection(Connnection))
99
{
100
SqlCommand com = new SqlCommand(ReadSql, conn);
101
conn.Open();
102
object CountResult = com.ExecuteScalar();
103
conn.Close();
104
Console.WriteLine("數據記錄數為:{0}",CountResult);
105
}
106
}
107
108
/**////
109
/// 根據id查詢;
110
///
111
private void Id_SelectById()
112
{
113
string ReadSql = "select * from Table_Id where Id="+300000;
114
using (SqlConnection conn = new SqlConnection(Connnection))
115
{
116
SqlCommand com = new SqlCommand(ReadSql, conn);
117
conn.Open();
118
object IdResult = com.ExecuteScalar();
119
Console.WriteLine("Id為{0}", IdResult);
120
conn.Close();
121
}
122
}
123
124
/**////
125
/// Guid測試;
126
///
127
private void Guid_InsertTest(int count)
128
{
129
string InsertSql = "insert into Table_Guid ([Value]) values ({0})";
130
using (SqlConnection conn = new SqlConnection(Connnection))
131
{
132
conn.Open();
133
SqlCommand com = new SqlCommand();
134
for (int i = 0; i < count; i++)
135
{
136
com.Connection = conn;
137
com.CommandText = string.Format(InsertSql, i);
138
com.ExecuteNonQuery();
139
}
140
}
141
}
142
143
/**////
144
/// Guid格式將數據庫讀到Table
145
///
146
private void Guid_ReadToTable(int count)
147
{
148
string ReadSql = "select top "+count.ToString()+" * from Table_GuID";
149
using (SqlConnection conn = new SqlConnection(Connnection))
150
{
151
SqlCommand com = new SqlCommand(ReadSql, conn);
152
SqlDataAdapter adapter = new SqlDataAdapter(com);
153
DataSet ds = new DataSet();
154
adapter.Fill(ds);
155
Console.WriteLine("數據記錄為:{0}", ds.Tables[0].Rows.Count);
156
}
157
}
158
159
/**////
160
/// 數據記錄行數測試
161
///
162
private void Guid_Count()
163
{
164
string ReadSql = "select Count(*) from Table_Guid";
165
using (SqlConnection conn = new SqlConnection(Connnection))
166
{
167
SqlCommand com = new SqlCommand(ReadSql, conn);
168
conn.Open();
169
object CountResult = com.ExecuteScalar();
170
conn.Close();
171
Console.WriteLine("數據記錄為:{0}", CountResult);
172
}
173
}
174
175
/**////
176
/// 根據Guid查詢;
177
///
178
private void Guid_SelectById()
179
{
180
string ReadSql = "select * from Table_Guid where Guid='C1763624-036D-4DB9-A1E4-7E16318C30DE'";
181
using (SqlConnection conn = new SqlConnection(Connnection))
182
{
183
SqlCommand com = new SqlCommand(ReadSql, conn);
184
conn.Open();
185
object IdResult = com.ExecuteScalar();
186
Console.WriteLine("Guid為{0}", IdResult);
187
conn.Close();
188
}
189
}
190
}
191
192
}
193
3.數據庫的插入測試
測試1
數據庫量為:100條
運行結果

測試2
數據庫量為:10000條
運行結果

測試3
數據庫量為:100000條
運行結果

測試4
數據庫量為:500000條
運行結果

4.將數據讀到DataSet中
測試1
讀取數據量:100
運行結果

測試2
讀取數據量:10000
運行結果

測試3
讀取數據量:100000
運行結果

測試4
讀取數據量:500000
運行結果

4.記錄總數測試
測試結果

5.指定條件查詢測試
查詢數據庫中第300000條記錄,數量記錄量為610300.

4.總結:
使用Guid作主鍵速度并不是很慢,它反而要比使用自動增長型的增量速度還要快.
5.參考:
http://www.cnblogs.com
http://www.cnblogs.com/leadzen/archive/2008/05/10/1191010.html
測試代碼下載
精彩評論:
周強:
對作者的測試環境有點小小的提議:
1.表的字段設計問題。我注意到你的測試表的設計都只有連個字段,一個PK列,一個VALUE。其中VALUE的數據庫類型是Varchar(50).而 在實際插入值的時候,Value所占的實際字節數沒有超過6B。也就是說,對于自增表,一行數據所占用的字節數為少于20B(Id列為int型4字 節,value列少于等于6字節,另外數據行存儲時需要10個字節的系統開銷);而對于GUID表,GUID列占用16個字節,VALUE列少于6字節, 再加10字節的開銷,總數少于等于32字節。也就是說對于自增表,一個數據頁面大約可存儲8060/20=403行(對于你的測試表來說會多余403行, 因為VALUE列占用的字節數小于6)。而對于GUID表,8060/32=251行。為什么要算這個帳呢?因為偏偏GUID列是PK列,當一個頁面存儲 滿以后,再向GUID表插入數據,數據庫就可能要發生分頁操作。從你的測試結果也可以看出來,當插入的數據量逐漸增大的時候,GUID表所消耗的時見反而 曾多了,我估計應該就是這個原因。而自增表在插入的時候,由于獲得自增列的值數據庫要進行一次讀操作,所以,在插入數據量較小的時候,占用的時間比 GUID表多。另外,在實際運用中,一個表的一行數據只占用32字節的情況可能少之又少,GUID做PK列,性能可能下降的更厲害。
2.GUID占用的字節數多了,存儲空間肯定不是問題。但是一個頁面上的記錄數卻少了,也就是說數據庫在讀取的時候,一次IO操作的命中率肯定會減小了。如果表中的數據行數特別巨大,這方面的性能就不得不考慮了
所以,自增和GUID大家看著用,哪個合適用哪個。