【发布时间】:2020-03-05 15:00:01
【问题描述】:
我尝试生成 700 万个不重叠的随机字符串。(字符串长度必须为 2 到 4)
但是,我的代码用了 28023 毫秒来生成 700 万个不重叠的字符串。
我不知道如何高效地生成 700 万个不重叠的字符串。
我尝试使用 hashmap、list、... 因为我需要一个键值类型
HashMap<String, Integer> map = new HashMap();
long start = System.currentTimeMillis();
for(int i = 0 ; i < 7000000 ; ) {
int MAX_LENGTH = 4;
int MIN_LENGTH = 2;
StringBuffer temp = new StringBuffer();
Random rnd = new Random();
int length = rnd.nextInt(MAX_LENGTH - MIN_LENGTH + 1) + MIN_LENGTH; // 문자열 길이 랜덤(2~4자리)
for (int j = 0; j < length; j++) {
int rIndex = rnd.nextInt(2);
switch (rIndex) {
case 0:
// a-z(소문자)
temp.append((char) ((int) (rnd.nextInt(26)) + 97));
break;
case 1:
// A-Z(대문자)
temp.append((char) ((int) (rnd.nextInt(26)) + 65));
break;
}
}
String str = temp.toString();
if(!map.containsKey(str)) {
map.put(str, rnd.nextInt());
i++;
}
}
long end = System.currentTimeMillis();
System.out.println("Setup Performance : " + (end - start));
我的代码用了 28023 毫秒来生成 700 万个不重叠的字符串。
【问题讨论】:
-
一个建议是将
Random rnd = new Random();移出循环。不过,这并不能完全解决您的问题。 -
不到半分钟?有什么问题?
-
还将
StringBuffer替换为StringBuilder并将实例化移动到循环前(创建一次)并在每次迭代中使用setLength(0)。显着消除 GC。 -
您正在使用 52 个字母:A-Za-z。将您的字符串想象为以 52 为基数的 2、3 或 4 位数字。在该范围内选择一个数字并以 52 为基数表示。有很多方法可以从一个范围内生成非重复随机数,例如格式保留加密.
标签: java string algorithm random