Java listMapComparison

package bookexample;

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

public class ListPerformanceTest {

	
	
	public static void listMapComparison(){
		
		int times = 20000;
		
		ArrayList list = new ArrayList<>();
		Map<Integer, Integer> Map = new HashMap<Integer, Integer>();
		
		for(int i = 0; i < 100000; i ++)
			list.add(i);  //0, 1, 2 , 3 
		for(int i = 0; i < 100000; i ++)
			Map.put(i, i);
		
		
		long t1 = System.currentTimeMillis();
		int a = 1;
		for(int i = 0; i < times; i ++){
			if(list.contains(95555)){
				a = 0;
			}
		}
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1 + "ms with list"); 
		
		t1 = System.currentTimeMillis();
		a = 1;
		for(int i = 0; i < times; i ++){
			if(Map.containsKey(95555)){
				a = 0;
			}
		}
		t2 = System.currentTimeMillis();   
		System.out.println(t2-t1 + "ms with map");	 
	}
	
	
	public static void listAddDynamically(){

		int initSize = 10000000;
		
		ArrayList<Integer> list = new ArrayList<Integer>();
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		long t1 = System.currentTimeMillis();
		for(int i = 0; i < initSize; i++){
			list.add(123);
			map.put(i, i);
		}
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1 + "ms with empty "); 
		
		ArrayList<Integer> list2 = new ArrayList<Integer>(initSize);
		HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>(initSize);
		t1 = System.currentTimeMillis();
		for(int i = 0; i < initSize; i++){
			list2.add(123);	
			map2.put(i, i);	
		}
		
		t2 = System.currentTimeMillis();
		System.out.println(t2-t1 + "ms with init "); 
		
	}
	
	public static void main(String[] args) {
		
		listMapComparison();
		listAddDynamically();
		

	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值