File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes String Concatenation Finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "String Concatenation Finally" Watch "String Concatenation Finally" New topic

String Concatenation Finally

Vikas Aggarwal
Ranch Hand

Joined: Jun 22, 2001
Posts: 140
Hi All,

This has probably been discussed many times. But I have categorised my doubts. I have lots of old servlets in which "+" operator has been used thousand times. On the profile it shows that string objects are the highest in number.

They have been used like this:

out.println("My Test Info "+info+" Is Not Recent. "+testNumber"+ Is Wrong. This needs to be "+newTestNumber+"");

The alternatives that I have found are:

A. Use StringBuffer

But that meakes perceived page response time to be slower. Also it is not very possible to replace all "+" operator from all servlets (400 servlets) to have StringBuffer.
But if it has to be done then we will spend the effort and time.

B. Use StringBuilder

Same as String Buffer with added complexity of Sychronisation issues

C. Do something like this:

out.println("My Test Info ");out.print(info);out.print("Is Not Recent. ");out.print(testNumber);out.print("+ Is Wrong. This needs to be ");out.print(newTestNumber);

Is there any other method to minimise the string object creation in my case? Which one of above three is better and faster.


Vikas Aggarwal
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
Originally posted by Vikas Aggarwal:

out.println("My Test Info "+info+" Is Not Recent. "+testNumber"+ Is Wrong. This needs to be "+newTestNumber+"");

I do not think there is anything wrong in this.The slice at which you have profiled your application might have had a lots of string objects.
As long as you do not hold any unnecessay references to those objects , thats ok.When required GC can collect the memory back.

Rahul Bhattacharjee
LinkedIn - Blog
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

Moved from servlets to Java In General (Intermediate)

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
I agree. Here's the link:
subject: String Concatenation Finally
jQuery in Action, 3rd edition