There are currently three ways to get milliseconds in Java:

System.currenttimemillis ();

Calendar.getinstance ().getTimeInmillis ();

New Date().gettime ();

The code tests are as follows:

public class TimeTest { private static int LOOP_NUM = 1000000; public static void main(String[] args) { long t1 = System.currentTimeMillis(); testSystem(LOOP_NUM); long t2 = System.currentTimeMillis(); System.out.println("testSystem:" + (t2 - t1)); t1 = System.currentTimeMillis(); testCalender(LOOP_NUM); t2 = System.currentTimeMillis(); System.out.println("testCalender:" + (t2 - t1)); t1 = System.currentTimeMillis(); testDate(LOOP_NUM); t2 = System.currentTimeMillis(); System.out.println("testDate:" + (t2 - t1)); } // test System.currentTimeMillis() private static void testSystem(int loopNum) { for (int i=0; i<loopNum; i++) { long currentSystemTime = System.currentTimeMillis(); } } // test Calendar.getInstance().getTimeInMillis() private static void testCalender(int loopNum) { for (int i=0; i<loopNum; i++) { long currentTime = Calendar.getInstance().getTimeInMillis(); } } private static void testDate(int loopNum) { for (int i=0; i<loopNum; i++) { long currentTime = new Date().getTime(); }}}Copy the code

Output result:

testSystem:42
testCalender:417
testDate:36
Copy the code

Thus it can be seen

  • New Date().getTime() has the highest performance,Some devices may have the highest system.currentTimemillis ().
  • System.currenttimemillis () is second only to new Date().getTime() in performance.
  • Calendar.getinstance ().getTimeInmillis () has the lowest performance.

If you are concerned about performance-related issues, minimize the use of calendar.getInstance ().getTimeInmillis () when using timestamps.