Creating a general Java object question

Which is better for memory management or for any other reason, or the two scenarios are the same:

Calendar currentDateTime = Calendar.getInstance();
int i= foo.getSomething(currentDateTime);
Bar bar= foo.getBar(currentDateTime);

Another code block:

int i= foo.getSomething(Calendar.getInstance());
Bar bar= foo.getBar(Calendar.getInstance());

The general question is whether it is better to get an instance of the object, and then use this instance when necessary, or each time you need to get getInstance (). And the answer changes if it does not deal with a single, but does a simple POJO?

+3
source share
8 answers

For a singleton this does not matter much. Using a temporary variable, you save the overhead of calling the function, but nothing more - the same object is returned every time.

POJO, , , . , , .

, , . , , , .

0

, . Calendar.getInstance() , .

, , getSomething() getBar() , foo . , , .

EDIT: , Calendar.getInstance(), . , .

EDIT 2: , . , Calendar . , , . , .

+7

- ( , ). getInstance() . , . , .

- .

long currentDateTime = System.currentTimeMillis();

,

int currentDay = (int)(System.currentTimeMillis() / 86400000);

: , getInstance() , . ~ 20 . currentTimeMillis() 140 .

Calendar.getInstance() took on average 20088 ns. java.util.GregorianCalendar[time=1294086899359 ... deleted ...]
System.currentTimeMillis() took on average 938 ns. 1294086899377

int runs = 10000;
long start = System.nanoTime();
Calendar cal = null;
for(int i=0;i<runs;i++)
    cal = Calendar.getInstance();
long time = System.nanoTime() - start;
System.out.println("Calendar.getInstance() took on average "+time/runs+" ns. "+cal);

long start2 = System.nanoTime();
long now = 0;
for(int i=0;i<runs;i++)
    now = System.currentTimeMillis();
long time2 = System.nanoTime() - start2;
System.out.println("System.currentTimeMillis() took on average "+time2/runs+" ns. "+now);
+2
  • CPU
  • .

, . .

0

: 1. - , , , . 2. - POJO. getInstance() , . , .

, , . factory , . , (.. ), new . , , , , factory .

, , . ? , ? .

0

, , , / .

0

. , , , .

, Calendar. . , , 23:59:59.875, 00:00:00.007. ?

. .

: , . .

0
  • CPU
  • .

The garbage collector can collect a calendar instance immediately after the last use of the link to it.

0
source

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


All Articles