简体   繁体   中英

Difference between System.currentTimeMillis() and Date getTime()?

I was hoping to squeeze a tiny performance gain out of many calls to a function that returns a timestamp. The function looks like this:

public static long get_now_ms(){
    // returns number of MILLISECONDS since epoch
    java.util.Date d = new java.util.Date();
    return d.getTime();
}

Can I just replace this with:

public static long get_now_ms(){
    // returns number of MILLISECONDS since epoch
    return System.currentTimeMillis();
}

I know that Date internally uses System.currentTimeMillis(). My question is more whether or not daylight savings time or time zone could ever lead to a difference in result with these two approaches. I imagine this may come up with Calendar objects, but not Date objects, but would love some clarification on this.

I know I will likely not see an appreciable difference in performance in a real-world application, but would nevertheless like to know the answer.

Thanks!

No difference, except for the very slight lag caused by allocating a Date object.

From the javadoc the the default constructor of Date :

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

A Date is just a thin wrapper around the epoch milliseconds, without any concept of timezones. Only when rendered to a String is timezone considered, but that is handled by the Locale class.

I would suggest running a unit test (ex. https://gist.github.com/ledlogic/8532028 ). I saw only a slight overall benefit to running the System.currentTimeMillis versus the (new Date()).getTime().

1 billion runs: (1000 outer loops, 1,000,000 inner loops):
    System.currentTimeMillis(): 14.353 seconds
    (new Date()).getTime(): 16.668 seconds

Individual runs would sometimes be slightly biased toward the later approach - depending on your system activity.

No difference, and Calendar.getTimeInMillis() is also same. because the return results is the number of milliseconds since January 1, 1970, 00:00:00 GMT. you will get a same long value whereever you are all over the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM