获取时间戳的三种方法的效率比较

1.System.currentTimeMillis()

System类中的currentTimeMillis()方法是三种方式中效率最好的,运行时间最短。开发中如果设计到效率问题,推荐使用此种方式获取。

2.new Date().getTime()

除了System类,使用量很大的应该就是Date类了,但date类中获取时间戳并不是最有效率的,翻看他的源码:
无参构造如下
public Date() {
this(System.currentTimeMillis());
}
从源码可以看出,new Date()其实就是调用了System.currentTimeMillis(),再传入自己的有参构造函数。
不难看出,如果只是仅仅获取时间戳,即使是匿名的new Date()对象也会有些许的性能消耗,从提升性能的角度来看,只是仅仅获取时间戳,不考虑时区的影响,
直接调用System.currentTimeMillis()会更好一些。

3.Calendar.getInstance().getTimeInMillis()

这种方式其实是速度最慢,看其源码就会发现,Canlendar是区分时区的,因为要处理时区问题会耗费很多的时间。

package com.example.java_algorithms.javaBasic.time;

import java.util.Calendar;
import java.util.Date;

/**
 * 三种时间戳获取方式效率比较
 */
public class TimeStampComparable {
        private static long _TEN_THOUSAND=10000;
        public static void main(String[] args) {
            long times=1000*_TEN_THOUSAND;
            long t1=System.currentTimeMillis();
            testSystem(times);
            long t2=System.currentTimeMillis();
            System.out.println(t2-t1);

            testCalander(times);
            long t3=System.currentTimeMillis();
            System.out.println(t3-t2);

            testDate(times);
            long t4=System.currentTimeMillis();
            System.out.println(t4-t3);
            /**
             testSystem:28
             testCalander:1513
             testDate:29
             */
        }

        public static void testSystem(long times){//use 188
            for(int i=0;i<times;i++){
                long currentTime=System.currentTimeMillis();
            }
        }

        public static void testCalander(long times){//use 6299
            for(int i=0;i<times;i++){
                long currentTime= Calendar.getInstance().getTimeInMillis();
            }
        }

        public static void testDate(long times){
            for(int i=0;i<times;i++){
                long currentTime=new Date().getTime();
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锐行织梦者

谢谢您的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值