java8 HashMap 性能质疑

我们都知道java8对HashMap的实现进行了优化(链表超过一定长度则采用红黑树处理),但以下简单的代码证明:java8中HashMap存在严重的性能问题。

import java.util.HashMap;
import java.util.Map;

/**
 * java8 在hashCode不均匀的情形下 性能极差(相比6与7)
 * java8对于链表长度太长(默认超过8)时,链表就转换为红黑树,利用红黑树快速增删改查的特点提高HashMap的性能
 * 为什么采用红黑树反而起来相反的效果?
 * 

* Created by donghq on 17/7/28. */ public class TestJava8HashMap { public static final int TIMES = 40000; //4万 public static void main(String[] args) { Map users = new HashMap(TIMES); User u; long b = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) { u = new User(String.valueOf(i), i); users.put(u, String.valueOf(i)); } long e = System.currentTimeMillis(); System.out.println("put耗时: " + (e - b) + " ms"); b = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) { u = new User(String.valueOf(i), i); users.get(u); } e = System.currentTimeMillis(); System.out.println("get耗时: " + (e - b) + " ms"); } } class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (age != user.age) return false; return name != null ? name.equals(user.name) : user.name == null; } @Override public int hashCode() { //int result = name != null ? name.hashCode() : 0; //result = 31 * result + age; //使hashCode 极不均匀 return 1; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }

以下是测试结果:

java8 HashMap 性能质疑_第1张图片

 

转载于:https://my.oschina.net/u/3601137/blog/1492001

你可能感兴趣的:(java,数据结构与算法)