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

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

 

posted @   ado-geek  阅读(332)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示