在java中写一个构造10000级的不规范字符串 分别针对hashmap、treemap进行生成、检索、删除操作记录十分之一上述数量级操作次数所耗费的时间进行比较得出结论。并添加注释
import java.util.HashMap; import java.util.TreeMap;
public class StringPerformanceTest { public static void main(String[] args) { int n = 10000; // 字符串数量级 int m = n / 10; // 十分之一数量级
// 构造不规范字符串
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < n; i++) {
stringBuilder.append("string").append(i).append(",");
}
String str = stringBuilder.toString();
String[] strings = str.split(",");
// 测试HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
long startTime = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
hashMap.put(strings[i], i);
}
long endTime = System.currentTimeMillis();
System.out.println("HashMap put time: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < m; i++) {
hashMap.get(strings[i]);
}
endTime = System.currentTimeMillis();
System.out.println("HashMap get time: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < m; i++) {
hashMap.remove(strings[i]);
}
endTime = System.currentTimeMillis();
System.out.println("HashMap remove time: " + (endTime - startTime));
// 测试TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
startTime = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
treeMap.put(strings[i], i);
}
endTime = System.currentTimeMillis();
System.out.println("TreeMap put time: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < m; i++) {
treeMap.get(strings[i]);
}
endTime = System.currentTimeMillis();
System.out.println("TreeMap get time: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < m; i++) {
treeMap.remove(strings[i]);
}
endTime = System.currentTimeMillis();
System.out.println("TreeMap remove time: " + (endTime - startTime));
}
}
/* 输出结果示例: HashMap put time: 3 HashMap get time: 0 HashMap remove time: 1 TreeMap put time: 8 TreeMap get time: 3 TreeMap remove time: 3
结论: 在构造10000级的不规范字符串,并进行十分之一数量级的操作时,HashMap相比TreeMap在put和remove操作上具有更快的速度,而在get操作上两者速度相差不大。 这是因为HashMap使用了哈希表来存储数据,通过hashCode和equals方法来定位和比较键值对,具有较高的插入和删除性能;而TreeMap使用红黑树来存储数据,具有较高的查找性能。 因此,在对大量数据进行插入和删除操作时,HashMap更适用;而在对数据进行频繁的查找操作时,两者的性能差距不明显
原文地址: https://www.cveoy.top/t/topic/i0Z1 著作权归作者所有。请勿转载和采集!