【轉載】GUID vs INT Debate

来源:http://www.cnblogs.com/bluedoctor/archive/2016/01/07/5109434.html
-Advertisement-
Play Games

普通GUID 會發生很大的頁分裂情況,這在一個表反覆修改的情況下,可能會明顯影響查詢速度。


I recently read a blog post on what was better using GUIDs or Integer values. This is been an age long debate and there are advocates in both camps stressing on the disadvantages of the other. Well both implementations have their advantages and disadvantages. At the outset, I shall mention that the answer to this debate is: IT DEPENDS! J

It is highly dependent on your database design, migration needs and overall architecture.  There is a good reason why SQL Server replication uses GUIDs to track the changes to the replicated articles. So, it is not that the usage to GUIDs is necessarily a bad practice. SQL Server Books Online lists the following disadvantages for uniqueidentifier data type:

  • The values are long and obscure. This makes them difficult for users to type correctly, and more difficult for users to remember.
  • The values are random and cannot accept any patterns that may make them more meaningful to users.
  • There is no way to determine the sequence in which uniqueidentifier values were generated. They are not suited for existing applications that depend on incrementing key values serially.
  • At 16 bytes, the uniqueidentifier data type is relatively larger than other data types, such as 4-byte integers. This means indexes that are built using uniqueidentifier keys might be relatively slower than indexes using an int key.

If you are using NEWID function in SQL Server, then this generates random UUIDs which have a huge domain but the chances of GUID collisions are always there though the probability is very slim in nature. If you are using NEWID function to generate uniqueidentifiers as row identifiers in your table, then you need to think again! Uniqueness of the row should be enforced using a Unique or Primary Key constraint on the table. NewSequentialID function uses identification number of the computer network card plus a unique number from the CPU clock to generate the uniqueidentifier (Reference article). So the chance of getting a globally unique value is practically guaranteed as long as the machine has a network card. Moreover, possibility of a GUID collision while using NewSequentialID is virtually impossible.

 

Given that you have a beefy server, the above time difference would not make much of a difference unless and until you only have a high number of concurrent INSERT workload on the server or during a Data Load operation which would cause a significant impact. What is interesting to note is that the fragmentation on the tables after the first batch of 1 million inserts.

Object Name

Index Name

Pages

Average Record Size

Extents

Average Page Density

Logical Fragmentation

Extent Fragmentation

tblGUID

cidx_tblGUID

9608

51.89

1209.00

69.27

99.14

0.25

tblSeqGUID

cidx_tblSeqGUID

6697

51.89

845.00

99.39

0.76

0.12

tblBigINT

cidx_tblBigINT

5671

43.89

714.00

99.95

0.48

0.14

tblINT

cidx_tblINT

5194

39.89

653.00

99.62

0.37

0.15

 

If you look at the above data, you will see that the random GUIDs have 99% logical fragmentation in the tables. This is due to the random nature of the GUIDs generated which end up causing high number of page splits in the database.

--------------

原文地址:http://blogs.msdn.com/b/sqlserverfaq/archive/2010/05/27/guid-vs-int-debate.aspx

上面的表格說明,普通GUID 會發生很大的頁分裂情況,這在一個表反覆修改的情況下,可能會明顯影響查詢速度。

那麼怎麼生成有序的GUID呢?下麵提供一種方法:

using System;
using System.Runtime.InteropServices;

namespace System
{
    public static class GuidEx
    {
        [DllImport("rpcrt4.dll", SetLastError = true)]
        private static extern int UuidCreateSequential(out Guid guid);
        private const int RPC_S_OK = 0;

        /// <summary>
        /// Generate a new sequential GUID. If UuidCreateSequential fails, it will fall back on standard random guids.
        /// </summary>
        /// <returns>A GUID</returns>
        public static Guid NewSeqGuid()
        {
            Guid sequentialGuid;
            int hResult = UuidCreateSequential(out sequentialGuid);
            if (hResult == RPC_S_OK)
            {
                return sequentialGuid;
            }
            else
            {
                //couldn't create sequential guid, fall back on random guid
                return Guid.NewGuid();
            }
        }
    }
}

詳細的內容,請看 http://stackoverflow.com/questions/665417/sequential-guid-in-linq-to-sql 討論。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • SELECT hp_patient.name, hp_ptorders.DrugName, hp_ptorders.Dosage,hp_ptorders.DosageUnitFROM hp_patientLEFT JOIN hp_ptordersON hp_patient.pid=hp_ptorde...
  • 一、 ASM(自動存儲管理)的來由:ASM是Oracle 10g R2中為了簡化Oracle資料庫的管理而推出來的一項新功能,這是Oracle自己提供的捲管理器,主要用於替代操作系統所提供的LVM,它不僅支持單實例,同時對RAC的支持也是非常好。ASM可以自動管理磁碟組並提供有效的數據冗餘功能。.....
  • 表:T_USERS,T_USER_EXCEPT_WORK,其中T_USERS中的主鍵ID和T_USER_EXCEPT_WORK中的外鍵都為數列SEQUENCE_USERS.Currval的自增長數列。更通俗的講就是:在T_USERS表中插入一條數據,通過觸發器在T_USER_EXCEPT_WORK插...
  • SQLServer資料庫的基礎知識的回顧 1)主數據文件:*.mdf 2)次要數據文件:*.ndf 3)日誌文件:*.ldf 每個資料庫至少要包含兩個文件:一個數據文件和一個日誌文件 如何查看SQL Server的幫助==================快捷鍵F1一、創建資料庫1.語法1 ...
  • 本文目錄列表:1、從MySQL提供的TO_DAYS和FROM_DAYS這對函數說起2、SQL Server日期時間粒度3、SQL Server周有關時間粒度4、總結語5、參考清單列表從MySQL提供的TO_DAYS和FROM_DAYS針對函數說起 學習和使用過MySQL的博友,大都知道MySQL提供...
  • 原文地址:http://blog.itpub.net/7478833/viewspace-441043/感謝作者in 和 exists區別in 是把外表和內表作hash join,而exists是對外表作loop,每次loop再對內表進行查詢。一直以來認為exists比in效率高的說法是不准確的。如...
  • 一個防止誤刪MSSQL資料庫的方法環境:Windows2008 R2 、SQL 2012今天發現一個有趣的現象,之前資料庫伺服器的其中幾個資料庫做過鏡像,不過現在已經刪除了,今天又要在那台伺服器上為一個庫搭建鏡像搭建鏡像的過程中,把鏡像機器的ip寫成了自己的ip,結果發現命令成功執行--備機上執行U...
  • 1 select * from sysobjects where xtype='PK'此條語句使用的場景: 當我們使用sql語句創建表的時候,可以給表中的id列添加check約束和標識列約束,主鍵約束... 當我們添加表成功後,進資料庫中區查看check約束的時候,是不會有check約束的名字的.....
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...