询问后这个问题比较顺序和非顺序的GUID,我试图表与顺序初始化的GUID主键比较上1 INSERT性能)newsequentialid()
,和2)的表与INT主键与顺序初始化identity(1,1)
。我希望后者是最快的,因为整数的宽度较小,并且生成顺序整数比顺序GUID似乎也更简单。但是令我惊讶的是,带有整数键的表上的INSERT显着慢于顺序GUID表。
这显示了测试运行的平均时间使用量(毫秒):
NEWSEQUENTIALID() 1977
IDENTITY() 2223
谁能解释一下?
使用了以下实验:
SET NOCOUNT ON
CREATE TABLE TestGuid2 (Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))
CREATE TABLE TestInt (Id Int NOT NULL identity(1,1) PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))
DECLARE @BatchCounter INT = 1
DECLARE @Numrows INT = 100000
WHILE (@BatchCounter <= 20)
BEGIN
BEGIN TRAN
DECLARE @LocalCounter INT = 0
WHILE (@LocalCounter <= @NumRows)
BEGIN
INSERT TestGuid2 (SomeDate,batchNumber) VALUES (GETDATE(),@BatchCounter)
SET @LocalCounter +=1
END
SET @LocalCounter = 0
WHILE (@LocalCounter <= @NumRows)
BEGIN
INSERT TestInt (SomeDate,batchNumber) VALUES (GETDATE(),@BatchCounter)
SET @LocalCounter +=1
END
SET @BatchCounter +=1
COMMIT
END
DBCC showcontig ('TestGuid2') WITH tableresults
DBCC showcontig ('TestInt') WITH tableresults
SELECT batchNumber,DATEDIFF(ms,MIN(SomeDate),MAX(SomeDate)) AS [NEWSEQUENTIALID()]
FROM TestGuid2
GROUP BY batchNumber
SELECT batchNumber,DATEDIFF(ms,MIN(SomeDate),MAX(SomeDate)) AS [IDENTITY()]
FROM TestInt
GROUP BY batchNumber
DROP TABLE TestGuid2
DROP TABLE TestInt
更新: 修改脚本以基于TEMP表执行插入,如下面的Phil Sandler,Mitch Wheat和Martin的示例中所示,我还发现IDENTITY的速度更快。但这不是传统的插入行的方式,而且我仍然不明白为什么实验起初会出错:即使我从原始示例中省略了GETDATE(),IDENTITY()仍然要慢得多。因此,似乎使IDENTITY()胜过NEWSEQUENTIALID()的唯一方法是准备要插入到临时表中的行,并使用此临时表以批量插入的方式执行许多插入。总而言之,我认为我们还没有找到这种现象的解释,而且IDENTITY()对于大多数实际用法似乎仍然较慢。谁能解释一下?
INT IDENTITY