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);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值