As known String is immutable in Java. I have the following method's body which return String:
Partner partner = context.getComponent(ComponentNames.PARTNER_COMPONENT_NAME);
String lastAccesDate = partner.getLastAccessDate();
if(lastAccesDate == null) {
return "";
}
lastAccesDate = new SimpleDateFormat(DATE_PATTERN).format(); //1
return lastAccesDate;
The thing is because of string immutability, a new String object will be created at //1, so actually I'll have two String Objects, the first one contains partner.getLastAccessDate();, the second one new SimpleDateFormat(DATE_PATTERN).format();. The overhead is not good, how can I avoid it?
lastAccesDate = new SimpleDateFormat(DATE_PATTERN).format();do? Theformatmethod must have aDateas an argument. Also, although it is true that a newStringis created when using the format (I looked at the Java source code) this is not because of String immutability, but despite immutability. It is theoretically possible that theformatmethod would callString.intern(String)in order to save memory since theStringcannot be changed anyway.