数据库中使用自增量字段与Guid字段作主键的性能对比(补充篇)

     数据库中使用自增量字段与Guid字段作主键的性能对比(补充篇)  

      我在发表过“据库中使用自增量字段与Guid字段主键的性能对比”这篇文章后,得到博客园各园友的很多评价,大家对我的测试方法也提出一些改进的方法。让我吃惊的是一园友提出:把guid和id的测试顺序颠倒一下,看下结果。今天就再测试一下,欢迎各园友提出更好的测试方案。     

1.测试环境  

     操作系统:windows server 2003 R2 Enterprise Edition Service Pack 2

  数据库:MS SQL 2008 Express

  CPU:Intel(R) Pentium(R) 4 CPU 3.40GHz

  内存:DDRⅡ 667  1G

  硬盘:WD 80G

2.数据库脚本  

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     
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

首先看一下测试代码:

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;

namespace GuidTest
ExpandedBlockStart.gifContractedBlock.gif
{
   
class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif   
{
       
string Connnection = @"server=pc13\sql2008express;database=testDemo;Integrated Security=true;";
       
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Program app
= new Program();
           
int Count = 3000;
            List
<long> idList = new List<long>(10);
            List
<long> guidList = new List<long>(10);

            Console.WriteLine(
"数据记录数为{0}", Count);
            Console.WriteLine(
"-----------------------------------------");

           
// Guid测试;
            Console.WriteLine("Guid测试");
            Stopwatch WatchGuid
= new Stopwatch();
            Console.WriteLine(
"开始测试");
            Console.WriteLine(
"测试中");
           
for (int i = 0; i < 10; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                WatchGuid.Start();
               
// app.Guid_InsertTest(Count);
               
// app.Guid_ReadToTable(Count);
               
//app.Guid_Count();
               
//查询第3000条记录;
                app.Guid_SelectById();         
                WatchGuid.Stop();
                guidList.Add(WatchGuid.ElapsedMilliseconds);
            }

            app.PrintTimer(guidList);
            Console.WriteLine(
"-----------------------------------------");

ExpandedSubBlockStart.gifContractedSubBlock.gif           
/**/////自动id增长测试;
            //Console.WriteLine("自动增长id测试");
           
//Stopwatch WatchId = new Stopwatch();
           
//Console.WriteLine("开始测试");
           
//Console.WriteLine("测试中");
           
//for (int i = 0; i < 10; i++)
           
//{
           
//    WatchId.Start();
           
//    //app.Id_InsertTest(Count);
           
//    //app.Id_ReadToTable(Count);
           
//    //app.Id_Count();
           
//    //查询第3000条记录;
           
//    app.Id_SelectById();
           
//    WatchId.Stop();
           
//    idList.Add(WatchId.ElapsedMilliseconds);
           
//}
           
//app.PrintTimer(idList);
           
//Console.WriteLine("-----------------------------------------");


            Console.Read();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 输出时间;
       
/// </summary>
       
/// <param name="list"></param>

        private void PrintTimer(List<long> list)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine();
           
long sum = 0;
           
for (int i = 0; i < list.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                Console.WriteLine(
string.Format("第{0}次使用时间(毫秒):{1}", i + 1, list[i]));
                sum
+= list[i];
            }

            Console.WriteLine(
string.Format("平均时间(毫秒):{0}", sum / list.Count));
            Console.WriteLine(
"测试结束");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 自动增长id测试
       
/// </summary>

        private void Id_InsertTest(int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"自动增长id的写入数据测试");
           
string InsertSql = "insert into Table_Id ([Value]) values ({0})";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                conn.Open();
                SqlCommand com
= new SqlCommand();
               
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif               
{
                    com.Connection
= conn;
                    com.CommandText
= string.Format(InsertSql, i);
                    com.ExecuteNonQuery();
                }

            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 将数据读到Table
       
/// </summary>

        private void Id_ReadToTable(int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"自动增长id将数据读取到DataTable的测试");
           
string ReadSql = "select top " + count.ToString() + " * from Table_Id";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                SqlDataAdapter adapter
= new SqlDataAdapter(com);
                DataSet ds
= new DataSet();
                adapter.Fill(ds);
                Console.WriteLine(
"数据记录数为:{0}", ds.Tables[0].Rows.Count);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 数据记录行数测试
       
/// </summary>

        private void Id_Count()
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"自动增长id数据总记录数测试");
           
string ReadSql = "select Count(*) from Table_Id";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                conn.Open();
               
object CountResult = com.ExecuteScalar();
                conn.Close();
                Console.WriteLine(
"数据记录数为:{0}", CountResult);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 根据id查询;
       
/// </summary>

        private void Id_SelectById()
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"自动增长id根据id查询测试");
           
string ReadSql = "select * from Table_Id where Id=" + 215000;
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                conn.Open();
               
object IdResult = com.ExecuteScalar();
                Console.WriteLine(
"Id为{0}", IdResult);
                conn.Close();
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// Guid测试;
       
/// </summary>

        private void Guid_InsertTest(int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"Guid写入数据测试");
           
string InsertSql = "insert into Table_Guid ([Value]) values ({0})";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                conn.Open();
                SqlCommand com
= new SqlCommand();
               
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif               
{
                    com.Connection
= conn;
                    com.CommandText
= string.Format(InsertSql, i);
                    com.ExecuteNonQuery();
                }

            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// Guid格式将数据库读到Table
       
/// </summary>

        private void Guid_ReadToTable(int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"Guid将数据读取到DataTable的测试");
           
string ReadSql = "select top " + count.ToString() + " * from Table_GuID";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                SqlDataAdapter adapter
= new SqlDataAdapter(com);
                DataSet ds
= new DataSet();
                adapter.Fill(ds);
                Console.WriteLine(
"数据记录为:{0}", ds.Tables[0].Rows.Count);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 数据记录行数测试
       
/// </summary>

        private void Guid_Count()
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"将Guid数据类型读取到DataTable测试");
           
string ReadSql = "select Count(*) from Table_Guid";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                conn.Open();
               
object CountResult = com.ExecuteScalar();
                conn.Close();
                Console.WriteLine(
"数据记录为:{0}", CountResult);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif       
/**//// <summary>
       
/// 根据Guid查询;
       
/// </summary>

        private void Guid_SelectById()
ExpandedSubBlockStart.gifContractedSubBlock.gif       
{
            Console.WriteLine(
"根据Guid查询的测试");
           
string ReadSql = "select * from Table_Guid where Guid='9D54E0DC-4A07-4E00-8231-25BD21655145'";
           
using (SqlConnection conn = new SqlConnection(Connnection))
ExpandedSubBlockStart.gifContractedSubBlock.gif           
{
                SqlCommand com
= new SqlCommand(ReadSql, conn);
                conn.Open();
               
object IdResult = com.ExecuteScalar();
                Console.WriteLine(
"Guid为{0}", IdResult);
                conn.Close();
            }

        }

    }

}


为了消除上面的顾虑,每次仅使用一种方式测试(每次都注释不使用的代码)。

1.1.自增Id的写入测试。

 image

1.2.Guid的写入测试。

image

2.1.自增Id的读取到DataTable测试

image

2.2.Guid的读取到DataTable测试

image

3.1.自增Id的数据总数统计

image

3.2.Guid数据总数统计

image

4.1.自增Id的数据总数统计(手动找到第3000条数据的id,然后查询)

image

4.2.Guid的数据总数统计(手动找到第3000条数据的id,然后查询)

image

以上测试均属本人电脑上的测试。每次的测试结果都是测试好几次,然后才取其中的一组相对平均的结果。

补充(不是我不总结,其实一些实际的应用已经在上一篇中总结过了,再整理一下吧):
      1.测试的结果Guid作为主键在以上测试的性能还是优于自动增长Id的。对于Inner join的还没有测试。
      2.对于使用那种类型作为主键,还要根据具体的需要。在数据库迁移或者导入数据的时候自增量字段有可能会出现重复,这无疑是一场恶梦,而Guid格式无疑是首选。但是,使用Guid格式比较复杂,对于程序高度比较麻烦,毕竟Guid比较难记。
      3.自动增长的Id使用的是int型或者bigint型,它们分别占用存储空间为4个字节和8个字节,Guid是uniqueidentifier类型,它占用16个字节。从存储空间上来说,自动增长的Id更节省空间。     
      4.如果要搞分布式数据库的话,这自增量字段就有问题了。因为,在分布式数据库中,不同数据库的同名的表可能需要进行同步复制。一个数据库表的自增量值,就很可能与另一数据库相同表的自增量值重复了。

      我个人还是比较喜欢使用Guid作主键,因为它比较唯一,不管是任务时候它都是唯一的,数据库的导入与导出都不会出现主键重复的现象。
我个人的一些问题:

      1.我使用的是windows Live Writer写的文章,为了粘贴代码的方便性,我使用from Visual Studio插件粘贴代码,但是如果代码中含有中文,例如注释,粘贴后,每个汉字后面都会多出一个“?”,这个问题不知道怎么解决,我通过设置编码方式还是不能解决问题。

      2.在Windows Live Writer中怎样设置代码(打包后上传后)的下载的链接。

      另外:向喜欢数据库的园友,推荐一篇:SQL Server 查询处理中的各个阶段
      关于自动增长Id与Guid的介绍请参见:据库中使用自增量字段与Guid字段主键的性能对比

      测试代码

转载于:https://www.cnblogs.com/houleixx/archive/2009/07/29/SQL-id-guid.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值