How to get current time in java without creating an object every time?

I know that there are many os posts on how to get the current time in java. But I am planning on getAge Method code in the Persona class. The problem is that I need to get the current time every time the method is called. Let them say that a billion clients are executed by getMethod (with milliseconds, perhaps seconds of difference), a billion objects will be created for such a simple thing. The only thing I did was create a static element in Person, so Person will share the instance. But this does not prevent the creation of the object.

public class Person{ //Some Attributes private static Calendar now; private Calendar birthDate; public short getAge(){ now = Calendar.getInstance(); return (short) (( now.getTimeInMillis() - birthDate.getTimeInMillis())/ 31536000000L; }} 

If you know some library that is implemented without loss of this heap size. Tell me please.

Thanks.

+4
source share
3 answers

You can also instantiate the calendar once and keep calling:

 calendar.setTimeInMillis ( System.currentTimeMillis() ); 

to set the current time in the calendar instance and use this calendar object to calculate any date.

+5
source

No need to create Calendar , you can get long from the static method

 System.currentTimeMillis(); 
+6
source

With timestamps obtained using optimized tools, what additional processing / overhead will be required to make the resulting timestamp significant?

http://joda-time.sourceforge.net

If you want the library to work with date and time, go with Joda Time. I would not pounce on any job.

 DateTime dt = new DateTime(); // current time 

I believe that if performance is a key problem / limiting problem, then you run tests to ensure that any work you accept achieves non-functional results that outweigh the readability of the code.

0
source

Source: https://habr.com/ru/post/1443001/


All Articles