St.Antario
St.Antario

Reputation: 27375

Usage StringBuffer and String?

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?

Upvotes: 0

Views: 68

Answers (2)

Abhishek Goswami
Abhishek Goswami

Reputation: 41

see when you assign second time string to the String object lastAccessDate, there is no overhead as automaticaly garbage collector will free the space which occupied by first object because no object has reference to the same. so no need to worry about overhead

Upvotes: 0

sol4me
sol4me

Reputation: 15698

Use StringBuffer in case of multithreading(i.e. if you need a thread-safe, mutable sequence of character) otherwise use StringBuilder

Upvotes: 1

Related Questions