测试对象:
- ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap
适用场景:
- ArrayList:查找快,增删慢 LinkedList:增删快,查找慢
- HashSet:值去重,不排序 TreeSet:值去重,且排序(默认升序排序)
- HashMap:键去重,不排序 TreeMap:键去重,且排序(需手动排序)
测试方法:
- 计算不同数据结构的对象添加N个数据之后占用的内存大小
测试代码:
代码语言:javascript复制import java.util.*;
public class Main{
public static void main(String[] args) throws Exception {
// 清理JVM垃圾内存
System.gc();
// 计算当前JVM可用内存总量
long start = Runtime.getRuntime().freeMemory();
// 创建对象
List list = new ArrayList();
// List list = new LinkedList();
// Set set = new HashSet();
// Set set = new TreeSet();
// Map map = new HashMap();
// Map map = new TreeMap();
for (int i = 0; i < 6666; i ) {
list.add(i);
// set.add(i);
// map.put(i,i);
}
System.gc();
long end = Runtime.getRuntime().freeMemory();
// 1Mb = 1024kb , 1kb = 1024byte(字节)
System.out.println("ArrayList对象占内存:" (float) (end - start)/1024/1024 " Mb");
// System.out.println("LinkedList对象占内存:" (float)(end - start)/1024/1024 " Mb");
// System.out.println("HashSet对象占内存:" (float)(end - start)/1024/1024 " Mb");
// System.out.println("TreeSet对象占内存:" (float)(end - start)/1024/1024 " Mb");
// System.out.println("HashMap对象占内存:" (float)(end - start)/1024/1024 " Mb");
// System.out.println("TreeMap对象占内存:" (float) (end - start)/1024/1024 " Mb");
}
}
测试结果:
- ArrayList对象占内存:1.7834549 Mb
- LinkedList对象占内存:1.6663132 Mb
- HashSet对象占内存:1.5532990 Mb
- TreeSet对象占内存:1.5648727 Mb
- HashMap对象占内存:1.4536972 Mb
- TreeMap对象占内存:1.4656143 Mb
测试结论:
- 内存大小:TreeMap < HashMap < HashSet < TreeSet < LinkedList < ArrayList