生成大(dà)量随機字符串不(bù)同實現方式的(de)效率對比
發表時(shí)間:2020-10-18
發布人(rén):融晨科技
浏覽次數:67
在(zài)26位英文字母中随即選取10個(gè)字符組成字符串,産生一定數量的(de)唯一字符串,對比幾種方式:
1.使用 System.Security.Cryptography.RNGCryptoServiceProvider 生成 Random 的(de)種子(zǐ) 和(hé / huò) 使用普通聲稱随機數進行對比.
2.使用 IDictionary<TKey , TValue> 其中TKey是(shì) Int 型 存放字符串的(de)HashCode,TValue 是(shì) String 型,存放生成的(de)字符串,通過對比鍵判斷是(shì)否項是(shì)否已經存在(zài) 和(hé / huò) 使用 IList<T> 存儲字符串進行對比.
3.使用随機截取字符串 和(hé / huò) 随機字符串數組索引獲取組成字符串. 生成構建 Random 實例種子(zǐ)的(de)方法:
static int GetRandomSeed( ) { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider( ); rng.GetBytes( bytes ); return BitConverter.ToInt32( bytes , 0 ); } 生成随機字符串的(de)方法: static string GetRandomString( ) { StringBuilder sbPwd = new StringBuilder( ); Random random = new Random( GetRandomSeed( ) ); for ( int i = 0 ; i < length ; i++ ) { sbPwd.Append( strSource.Substring( random.Next( 0 , 25 ) , 1 ) ); //sbPwd.Append( sourceArray[random.Next( 0 , 25 )] ); } return sbPwd.ToString( ); }
對比結果: 1.使用 GetRandomSeed( )方法生成 Random 種子(zǐ) 并使用字符截取 使用IDictionary<int , string> 耗時(shí) 20688MS 産生重複項 359 生成項:1000000 2.不(bù)使用 GetRandomSeed( )方法生成 Random 種子(zǐ) 并使用字符截取 使用IDictionary<int , string> 耗時(shí) 1562547MS 産生重複項 127749442 生成項:100000 3.使用 GetRandomSeed( )方法生成 Random 種子(zǐ) 并使用字符串數組 使用IDictionary<int , string> 耗時(shí)36125MS 産生重複項 381 生成項:1000000(使用Char數組效率更低,随機取得Char轉換成String時(shí)要(yào / yāo)進行裝箱) 4.使用GetRandomSeed( )方法生成 Random 種子(zǐ) 并使用字符截取 使用IList<string> 耗時(shí) 214719MS 産生重複項2 生成項:100000(生成項越多耗時(shí)越長) 可見使用 System.Security.Cryptography.RNGCryptoServiceProvider 生成 Random 種子(zǐ) 産生的(de)效率要(yào / yāo)高很多,特别是(shì)要(yào / yāo)連續生成大(dà)量的(de)随機數,因爲(wéi / wèi) Random 生成值的(de)重複率非常低. 使用字符串的(de)HashCode對比字符串比直接對比字符串效率要(yào / yāo)高很多. 使用字符串截取比使用字符串數組效率要(yào / yāo)高點. function forumhottag_callback(data){ tags = data; } parsetag();