概述
第一个选项应该更快.您可以通过在使用之前调整集合大小来使其更快.通常,如果您期望少量重复:
Set undefined = new HashSet(pairs.size(), 1);
请注意,我使用1作为加载因子来防止任何大小调整.
出于好奇,我进行了测试(下面的代码) – 结果是(编译后):
测试1(注意:热身需要几分钟)
size of original list = 3,000 with no duplicates:
set: 8
arraylist: 668
linkedlist: 1166
测试2
size of original list = 30,000 – all strings identical:
set: 25
arraylist: 11
linkelist: 13
那种有道理:
>当有许多重复项时,List#contains将运行得相当快,因为可以更快地找到重复项并且分配大型集合哈希算法的成本正在受到影响
>当没有或很少重复时,该集合大幅度地获胜.
public class TestPerf {
private static int NUM_RUN;
private static Random r = new Random(System.currentTimeMillis());
private static boolean random = false; //toggle to false for no duplicates in original list
public static void main(String[] args) {
List list = new ArrayList<>();
for (int i = 0; i < 30_000; i++) {
list.add(getRandomString());
}
//warm up
for (int i = 0; i < 10_000; i++) {
method1(list);
method2(list);
method3(list);
}
NUM_RUN = 100;
long sum = 0;
long start = System.nanoTime();
for (int i = 0; i < NUM_RUN; i++) {
sum += method1(list);
}
long end = System.nanoTime();
System.out.println("set: " + (end - start) / 1000000);
sum = 0;
start = System.nanoTime();
for (int i = 0; i < NUM_RUN; i++) {
sum += method2(list);
}
end = System.nanoTime();
System.out.println("arraylist: " + (end - start) / 1000000);
sum = 0;
start = System.nanoTime();
for (int i = 0; i < NUM_RUN; i++) {
sum += method3(list);
}
end = System.nanoTime();
System.out.println("linkelist: " + (end - start) / 1000000);
System.out.println(sum);
}
private static int method1(final List list) {
Set set = new HashSet<>(list.size(), 1);
for (String s : list) {
set.add(s);
}
return set.size();
}
private static int method2(final List list) {
List undefined = new ArrayList<>();
for (String s : list) {
if (!undefined.contains(s)) {
undefined.add(s);
}
}
return undefined.size();
}
private static int method3(final List list) {
List undefined = new LinkedList<>();
Iterator it = list.iterator();
while (it.hasNext()) {
String value = it.next();
if (!undefined.contains(value)) {
undefined.add(value);
}
}
return undefined.size();
}
private static String getRandomString() {
if (!random) {
return "skdjhflkjrglajhsdkhkjqwhkdjahkshd";
}
int size = r.nextInt(100);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
char c = (char) ('a' + r.nextInt(27));
sb.append(c);
}
System.out.println(sb);
return sb.toString();
}
}
最后
以上就是香蕉短靴为你收集整理的java 唯一值_java – 在列表中查找唯一值的快速方法的全部内容,希望文章能够帮你解决java 唯一值_java – 在列表中查找唯一值的快速方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复