Java性能对比:HashMap vs TreeMap 在10000级不规范字符串上的操作
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(","); // 测试HashMapHashMap<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));// 测试TreeMapTreeMap<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: 3HashMap get time: 0HashMap remove time: 1TreeMap put time: 8TreeMap get time: 3TreeMap remove time: 3结论:在构造10000级的不规范字符串,并进行十分之一数量级的操作时,HashMap相比TreeMap在put和remove操作上具有更快的速度,而在get操作上两者速度相差不大。这是因为HashMap使用了哈希表来存储数据,通过hashCode和equals方法来定位和比较键值对,具有较高的插入和删除性能;而TreeMap使用红黑树来存储数据,具有较高的查找性能。因此,在对大量数据进行插入和删除操作时,HashMap更适用;而在对数据进行频繁的查找操作时,两者的性能差距不明显。/
原文地址: https://www.cveoy.top/t/topic/o4Ja 著作权归作者所有。请勿转载和采集!