Java常用数据结构内存大小比较

测试对象:

  • ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap

适用场景:

  • ArrayList:查找快,增删慢      LinkedList:增删快,查找慢
  • HashSet:值去重,不排序      TreeSet:值去重,且排序(默认升序排序)
  • HashMap:键去重,不排序    TreeMap:键去重,且排序(需手动排序)

测试方法:

  • 计算不同数据结构的对象添加N个数据之后占用的内存大小

测试代码:

import java.util.*;

public class Main{
	
	public static void main(String[] args) throws Exception {

		// 清理JVM垃圾内存
		System.gc();
		// 计算当前JVM可用内存总量
		long start = Runtime.getRuntime().freeMemory();
		// 创建对象
		List<Integer> list = new ArrayList<Integer>();
//		List<Integer> list = new LinkedList<Integer>();		
//		Set<Integer> set = new HashSet<Integer>();
//		Set<Integer> set = new TreeSet<Integer>();
//		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//		Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
		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
发布了117 篇原创文章 · 获赞 28 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq262593421/article/details/104181032