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

在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对比字符串比直接对比字符串效率要高很多.
使用字符串截取比使用字符串数组效率要高点.

转载于:https://www.cnblogs.com/doll-net/archive/2008/03/08/Random.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值