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?
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, , , . , , .
, , . , , , .
, . Calendar.getInstance() , .
, , getSomething() getBar() , foo . , , .
EDIT: , Calendar.getInstance(), . , .
EDIT 2: , . , Calendar . , , . , .
- ( , ). 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);
, . .
: 1. - , , , . 2. - POJO. getInstance() , . , .
, , . factory , . , (.. ), new . , , , , factory .
, , . ? , ? .
, , , / .
. , , , .
, Calendar. . , , 23:59:59.875, 00:00:00.007. ?
Calendar
23:59:59.875
00:00:00.007
. .
: , . .
The garbage collector can collect a calendar instance immediately after the last use of the link to it.
Source: https://habr.com/ru/post/1783284/More articles:Changing the background color when using the world map - mappingEXC_BAD_ACCESS with NSUserdefaults on iphone - iphoneCodeigniter Current Login - phpJava self-service program (automatic checksum) - javaAdding dynamic fields to java / swing form - javaWCF Validation Messages - messageSQLAlchemy equivalent to Django x.objects.extra ()? - pythonSQL Trigger для обновления другой таблицы - sqlRDBMS - SQL Max Value of a column based on a different column uniqueness - sqlcall back between two sites - communication between two sites - javascriptAll Articles