Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
优化随机字符串生成
背景
原来的随机字符串生成代码在Windows环境下就存在BUG,可参考Function RandomChars has bug · Issue #121 · gookit/goutil (github.com)
在Windows本地测试发现如果使用for循环重复生成随机字符串存在相同的情况,代码如下:
输出打印如下:
正好最近看到一篇关于随机字符串生成的文章,原文链接:Golang生成随机字符串的八种方式与性能测试-云社区-华为云 (huaweicloud.com),How to generate a random string of a fixed length in Go? - Stack Overflow
所以打算根据文章中提到的方法优化
strutil
的随机字符串生成方法实现
新增的方法有2个
nearestPowerOfTwo
和buildRandomString
,nearestPowerOfTwo
方法是求大于等于字符模板的最近的2的整数次幂,这个方法参考java8的hashmap的tableSizeFor函数,可参考文章:HashMap部分源码简析 | 柳门竹巷 (zhbblog.top)buildRandomString
主要用于根据输入的字符串模板,生成指定长度的随机字符串,具体原理请参考上诉链接结果
测试结果
现在在Windows本地测试结果如下,代码:
输出打印如下:
nearestPowerOfTwo方法
返回大于输入参数且最近的2的整数次幂的数方法测试如下,代码:
输入打印如下:
优化前后性能对比
优化前后性能对比,代码如下:
输出打印如下:
优化前后准确性对比
优化前后准确性对比,代码如下:
输出打印如下:
优化后实际效果仍有待完整测试