Java练习:HashMap键值的更新方法对比
在词频统计中,HashMap键值的更新方法有很多种。让我们比较一下运行速度。
import java.util.HashMap; public class Main { public static void main(String[] args) { String s = "I like JAVA Java java " + "You like JAVA Java java"; System.out.println("方法1耗时:" + WordCount.method1(s)); System.out.println("方法2耗时:" + WordCount.method2(s)); System.out.println("方法3耗时:" + WordCount.method3(s)); System.out.println("方法4耗时:" + WordCount.method4(s)); System.out.println("方法5耗时:" + WordCount.method5(s)); } } class WordCount { public static long method1(String s) { String[] words = s.split(" "); HashMap<String, Integer> mapCounter = new HashMap<>(); long t0 = System.nanoTime(); for(String word:words) { if (mapCounter.containsKey(word)) { // 原词频加1 mapCounter.put(word, mapCounter.get(word) + 1); } else { //没有这个词,词频1; mapCounter.put(word, 1); } } long t1 = System.nanoTime(); return t1-t0; } public static long method2(String s) { String[] words = s.split(" "); HashMap<String, Integer> mapCounter = new HashMap<>(); long t0 = System.nanoTime(); for(String word:words) { //没有这个词,原词频0; mapCounter.putIfAbsent(word, 0); // 原词频加1 mapCounter.put(word, mapCounter.get(word) + 1); //较快 } long t1 = System.nanoTime(); return t1-t0; } public static long method3(String s) { String[] words = s.split(" "); HashMap<String, Integer> mapCounter = new HashMap<>(); long t0 = System.nanoTime(); for(String word:words) { //获取原词频,没有这个词,原词频0;原词频加1 mapCounter.put(word, mapCounter.getOrDefault(word, 0) + 1); //最快 } long t1 = System.nanoTime(); return t1-t0; } public static long method4(String s) { String[] words = s.split(" "); HashMap<String, Integer> mapCounter = new HashMap<>(); long t0 = System.nanoTime(); for(String word:words) { //没有这个词,放入这个词,词频1;有这个词,则原词频加1 mapCounter.merge(word, 1, Integer::sum); //类的静态方法引用,最慢 } long t1 = System.nanoTime(); return t1-t0; } public static long method5(String s) { String[] words = s.split(" "); HashMap<String, Integer> mapCounter = new HashMap<>(); long t0 = System.nanoTime(); for(String word:words) { //没有这个词,放入这个词,词频1;有这个词,则原词频加1 mapCounter.merge(word, 1, (a,b)->a+b); //慢 } long t1 = System.nanoTime(); return t1-t0; } }
运行结果:
方法1耗时:36300
方法2耗时:15000
方法3耗时:12300
方法4耗时:57522400
方法5耗时:375000
最快的和最慢的速度相差几千倍。
浙公网安备 33010602011771号