安卓开发

关于Calendar.getInstance() 调用位置 对性

2019-03-12  本文已影响4人  搬砖中年人

private static Calendar cal = Calendar.getInstance();

public final static long getMsgid(long GwSeq) {

long res = 0;

cal.setTimeInMillis(System.currentTimeMillis());

long month = cal.get(Calendar.MONTH) + 1;

long day = cal.get(Calendar.DAY_OF_MONTH);

long hour = cal.get(Calendar.HOUR_OF_DAY);

long minute = cal.get(Calendar.MINUTE);

long seconds = cal.get(Calendar.SECOND);

res = month << 60 | day << 55 | hour << 50 | minute << 44 | seconds << 38 | GwSeq << 16 | getMsgIdSeq();

return res;

}

private static AtomicLong msgidseq = new AtomicLong(100l);

/**

 * 自增循环使用(msgid)

 */

private final static long getMsgIdSeq() {

long next = msgidseq.incrementAndGet();

if (next > 65535) {

synchronized (msgidseq) {

if (msgidseq.get() > 65535) {

msgidseq.set(100);

next = msgidseq.incrementAndGet();

} else {

next = msgidseq.incrementAndGet();

}

}

}

return next;

}

public static void main(String[] args) {

long start = System.currentTimeMillis();

for (int i = 0; i < 100000000; i++) {

getMsgid(123);

}

System.out.println(System.currentTimeMillis()-start+"ms");

如果

Calendar.getInstance() 在方法内声明

内存会根据CPU处理速度  程直线上升 

以上代码在方法外声明创建   2核4线程 处理时间为1543ms1亿次获取

如果

Calendar.getInstance() 在方法内声明

每秒处理速度为300万封顶 内存 直接上到600MB  因为每一次 调用

getInstance 都会去创建一个对象并非单例 而且 内部会创建一个int数组

在方法外声明 有一点要注意 就是每一次都要刷新 当前时间戳 否则 时间 永远都是 第一次

调用getInstance 的时间

上一篇 下一篇

猜你喜欢

热点阅读