您的位置:首页 > 其它

生成大量随机字符串不同实现方式的效率对比

2008-12-04 12:59 441 查看
在26位英文字母中随即选取10个字符组成字符串,产生一定数量的唯一字符串,对比几种方式:

1.使用 System.Security.Cryptography.RNGCryptoServiceProvider 生成 Random 的种子 和 使用普通声称随机数进行对比.

2.使用 IDictionary<TKey , TValue> 其中TKey是 Int 型 存放字符串的HashCode,TValue 是 String 型,存放生成的字符串,通过对比键判断是否项是否已经存在 和 使用 IList<T> 存储字符串进行对比.

3.使用随机截取字符串 和 随机字符串数组索引获取组成字符串.

生成构建 Random 实例种子的方法:

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

}
生成随机字符串的方法:

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 种子 并使用字符截取 使用IDictionary<int , string> 耗时 20688MS 产生重复项 359 生成项:1000000

2.不使用 GetRandomSeed( )方法生成 Random 种子 并使用字符截取 使用IDictionary<int , string> 耗时 1562547MS 产生重复项 127749442 生成项:100000

3.使用 GetRandomSeed( )方法生成 Random 种子 并使用字符串数组 使用IDictionary<int , string> 耗时36125MS 产生重复项 381 生成项:1000000(使用Char数组效率更低,随机取得Char转换成String时要进行装箱)

4.使用GetRandomSeed( )方法生成 Random 种子 并使用字符截取 使用IList<string> 耗时 214719MS 产生重复项2 生成项:100000(生成项越多耗时越长)

可见使用 System.Security.Cryptography.RNGCryptoServiceProvider 生成 Random 种子 产生的效率要高很多,特别是要连续生成大量的随机数,因为 Random 生成值的重复率非常低.

使用字符串的HashCode对比字符串比直接对比字符串效率要高很多.

使用字符串截取比使用字符串数组效率要高点.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐