How much I can rely on GUID in .Net?
How mu开发者_如何学运维ch I can rely on GUID in .Net ? My SA told me that
we will use GUID as primary keys in all tables.
I wonder the reliability of GUID as a primary key.
Can there be any chances that there will be duplicate ?
Should we really use this way ?
How about the performance ?
Any advise would be helpful for me.
This are some points for GUID which give you answer
Advantage:
- Unique across the server.
Disadvantage:
- String values are not as optimal as integer values for performance when used in joins, indexes and conditions.
- More storage space is required than INT.
You can read full post aobut this at : SQL SERVER – GUID vs INT – Your Opinion
You may want to take a look at these articles:
http://www.codinghorror.com/blog/2007/03/primary-keys-ids-versus-guids.html
http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html
Personally I use integers if I don't need to have primary keys to be unique across several tables and databases. I find it simpler to debug with 87
than 2A734AE4-E0EF-4D77-9F84-51A8365AC5A0
.
Yes, there can be a duplicate but it wont. The GUID is a 32 char long and each char can be 0-F (hexadecimal). That means 16^32 possibilities.
So if you generate 1 000 000 GUIDs every second for 10 years, the chance that you create a duplicate is around 1 / 1079028307080601418897053.
In my opinion a GUID is a very good primary key candidate as you can generate if from anywhere without first checking if it already exist in the database.
Thanks to the Birthday Paradox (Problem) you have around 50% of finding a duplicate if you generate 2^64 GUID... Are you happy? (this is because a fully random GUID is long 128 bits, so there are 2^128 different GUID. The birthday paradox tells us that if you have aproximatevely sqrt(2^128) GUID you have a 50% chance of a collision I say fully random GUID because there are some standard type of GUID where some digits are fixed. But .NET doesn't use these standards (read here http://en.wikipedia.org/wiki/Globally_unique_identifier) )
I'll add that if you problem is a problem of "speed" of the db, you should read this:
Improving performance of cluster index GUID primary key
For the most part you can assume they will never duplicate, If your ID in a table is set to be the Primary Key, then inserting a duplicate will error anyway.
An advantage is using these ID's in a web application is that users cant just test URLS with other IDs so in theory would bemore secure (although you should have server validation for permissions anyway)
Guids are statistically very highly likely to be unique and therefore are good candidates for primary keys if various systems are generating IDs and all of these need to be combined.
Eg. Working in an offline mode style and pushing back the change to the central db.
精彩评论