很多人喜欢用GUID作为数据表的主键,如果使用无序的GUID,当数据量很大的时候,插入性能会急剧下降,如果非要使用GUID,则可以实用有序的GUID,这样性能的影响会比较小。
public static Guid GenerateGuid() { byte[] guidArray = Guid.NewGuid().ToByteArray(); var baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; var days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = now.TimeOfDay; byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); Array.Reverse(daysArray); Array.Reverse(msecsArray); Array.Copy(daysArray,daysArray.Length - 2,guidArray,guidArray.Length - 6,2); Array.Copy(msecsArray,msecsArray.Length - 4,guidArray,guidArray.Length - 4,4); return new Guid(guidArray); }