Java/J2EE interview questions: – Is using StringBuffer always yields better performance than concatenation using +?

No, String Buffer need not yield a good performance over String concatenation using +.

The type of concatenation plays a major role in deciding performance. If the concatenation can be completely resolved at coimpile time then String concatenation using + will yield better results
On the other hand if concatenation is done at run time using StringBuffer is more advisable, since StringBuffer objects are resolved at run time

Following are the two programs one showing compile time resolution and other run time and thus showing where StringBuffer will be usefull

Compile time resolution:

This program takes String literals and performs concatenation using + as well as StringBuffer. Since the String literals could be resolved at compile time itself, this indicates a case of compile time resolution.

Code is self explanatory with proper comments given where ever required.

On executing the above code we get following result

Result:

Concatenation using + takes 0 millisecs
Concatenation using StringBuffer takes 63 millisecs
Performance using concatenation using + better than StringBuffer concatenation

Conclusion: Since the above case if of compile time resolution performance using + concatenation yields a better result

Run Time resolution:

Just a small modification to compile time code shown above can give us run time case for further analysis

We change the concatenation used above to String conResult =””; conResult = conResult +”Welcome to the World of Java” +”Performance” +”@”+”questpond”;
a similar change is done in StringBuffer . code snippet after change will look like
package com.questpond.measurePerformance;



Result :

Concatenation using + takes 47 millisecs
Concatenation using StringBuffer takes 32 millisecs
Performance using concatenation using StringBuffer better than + concatenation

Conclusion :

the above case clearly shows StringBuffer giving more performance as compared to + concatenation at run time

Overall final conclusion: Prefer StringBuffer whenever run time resolution concatenation is involved

View the following video on J2EE Design Pattern – Service Locator: –

Get more Java/J2EE interview questions

Regards,

View author’s other Java/J2EE interview questions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s