java的内存counter

假设需要在内存中维护一个计数器,在storm tuple来时更新计数器的值,最终统一提交到数据库
可以用commons-collection中的Bag或者MultiValueMap,不过效率不高.
用java的Map放Integer主要问题在于Integer是不可变类,每次需要构造新的对象,开销比较大,因此尝试了common-lang中的MutableInt和java.util中的AtomicInteger,这俩的效率不相上下.
不过最快的方式是在Map中放int数组...不过优势也不是特别明显




		int size = 10000000;

		// 1
		long start = System.currentTimeMillis();

		Bag bag = BagUtils.typedBag(new HashBag(), String.class);
		for (int i = 0; i < size; i++) {
			bag.add("" + (i % 100), 1);
		}
		System.out.println(bag.getCount("5"));
		System.out.println(System.currentTimeMillis() - start);

		// 2
		start = System.currentTimeMillis();

		MultiValueMap map = new MultiValueMap();
		for (int i = 0; i < size; i++) {
			map.put("" + (i % 100), 1);
		}
		int total = 0;
		Collection<Integer> co = (Collection<Integer>) map.get("5");
		for (Integer i : co) {
			total += i;
		}
		System.out.println(total);
		System.out.println(System.currentTimeMillis() - start);

		// 3
		start = System.currentTimeMillis();

		Map<String, AtomicInteger> map3 = new HashMap<>();
		for (int i = 0; i < size; i++) {
			String key = "" + (i % 100);
			AtomicInteger value = map3.get(key);
			if (value == null) {
				map3.put(key, new AtomicInteger(1));
			} else {
				value.addAndGet(1);
			}
		}
		System.out.println(map3.get("5"));
		System.out.println(System.currentTimeMillis() - start);

		// 4
		start = System.currentTimeMillis();

		Map<String, MutableInt> map4 = new HashMap<>();
		for (int i = 0; i < size; i++) {
			String key = "" + (i % 100);
			MutableInt value = map4.get(key);
			if (value == null) {
				map4.put(key, new MutableInt(1));
			} else {
				value.add(1);
			}
		}
		System.out.println(map4.get("5"));
		System.out.println(System.currentTimeMillis() - start);

		// 5
		start = System.currentTimeMillis();

		Map<String, Integer> map5 = new HashMap<>();
		for (int i = 0; i < size; i++) {
			String key = "" + (i % 100);
			Integer value = map5.get(key);
			if (value == null) {
				map5.put(key, new Integer(1));
			} else {
				map5.put(key, value + 1);
			}
		}
		System.out.println(map5.get("5"));
		System.out.println(System.currentTimeMillis() - start);

		// 6
		start = System.currentTimeMillis();

		Map<String, int[]> map6 = new HashMap<>();
		for (int i = 0; i < size; i++) {
			String key = "" + (i % 100);
			int[] value = map6.get(key);
			if (value == null) {
				map6.put(key, new int[] { 1 });
			} else {
				value[0] += 1;
			}
		}
		System.out.println(map6.get("5")[0]);
		System.out.println(System.currentTimeMillis() - start);

	
	

你可能感兴趣的:(count)