string buffer vs string builder in java

hi,

What are advantages, disadvantages, practical uses of each of
string buffer vs string builder in java  vs + operator vs concat metjod of string
Please advise. Any ideas, resources, sample code highly appreciated. thanks in advance
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

girionisCommented:
StringBuffer is synchronised, this is the only difference with StringBuilder.

Concatenating strings is an expensive operation since you recreate the new strings over and over again. But in most cases the compiler will turn a string concatenation into a StringBuilder object, so no real advantage here.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
krakatoaCommented:
girionis has explained.

Here is a rudimentary time trial -

import java.util.*;
class StringMeter {

StringBuffer sb;
StringBuilder sbldr;
char  [] chA;
final static int loops = 10000000;
static String halfString;
static String otherHalfString;


  public static void main(String[] args){

	StringMeter sm =new StringMeter();

	sm.sb = new StringBuffer(loops);
	sm.sbldr = new StringBuilder(loops);
	sm.chA = new char[loops];
	
	long sNans = System.nanoTime();

	for (int a=0;a<loops;a++){
		sm.sb.append((char)a);
	}

	halfString = sm.sb.substring(0,sm.sb.length()/2).toString();
	otherHalfString = sm.sb.substring((sm.sb.length()/2)).toString();

	long eNans = System.nanoTime();
	
	System.out.println("Buffer ops took "+(eNans-sNans));
	
	sNans = System.nanoTime();
	for (int a=0;a<loops;a++){
		sm.sbldr.append((char)a);
		
	}
	
	eNans = System.nanoTime();
	
	System.out.println("Builder ops took "+(eNans-sNans));
	
	sNans = System.nanoTime();

	for (int a=0;a<loops;a++){
		sm.chA[a]=(char)a;
		
	}
	
	eNans = System.nanoTime();
	
	System.out.println("Char array ops took "+(eNans-sNans));

	sNans = System.nanoTime();
	String fullString = halfString.concat(otherHalfString);
	eNans = System.nanoTime();
	//System.out.println("String concat took "+(eNans-sNans)+" nanosecs to produce \""+fullString+"\"");
	System.out.println("String concat took "+(eNans-sNans)+" nanosecs to produce a string of length "+fullString.length());

  }


}

Open in new window

0
dpearsonCommented:
One more point to make about this.  Back in the day thought it was better to write code like this:

int x = 10 ; int y = 20 ;
String msg = new StringBuffer() ;
msg.append("x value is ") ;
msg.append(x) ;
msg.append(" y value is ") ;
msg.append(y) ;
System.out.println(msg.toString()) ;

instead of:
System.out.println("x value is " + x + " y value is " + y) ;

But this turned out to be a very bad idea when the Java guys switched how string concatenation worked so it would use StringBuilder() instead of StringBuffer() behind the scenes.  So now the first set of code is slower than the second.

So the lesson is - as is true for lots of software - don't try to be too clever.  If you are doing simple string concatenation, you can avoid StringBuffer/StringBuilder.

The time to use them is when you're adding to a string in a loop.

Doug
0
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

krakatoaCommented:
Interesting as to why you say it was a really bad idea - you must have been surely doing millions of String operations to notice any significant impact?

BTW this : String msg = new StringBuffer() ; can't of course compile.
0
dpearsonCommented:
you must have been surely doing millions of String operations to notice any significant impact?

No not necessarily.  The performance hit comes from the extra calls to "synchronize" that are used by the StringBuffer api.

So using the code that includes explicit calls to StringBuffer in a multi-threaded application could cause it to run 2x slower (or worse) than the same code using StringBuilder.  That's because each call to synchronize essentially forces a memory synchronization event (so that all threads running on all CPU cores see the same state of main memory) - which in turn could limit the parallelism of the process as a whole or impact the CPU's cache performance.

So it's not the cost of the operation itself that's the issue - but the potential impact that could have on a larger multithreaded operation through hidden and unnecessary synchronization events.

On a single threaded program then it's fair to say the difference would be negligible (indeed it might be zero - not sure if there's any cost when there is no synchronization occurring?).

Doug

P.S. And yes I included a typo in my original code.  It should be StringBuffer on both sides...
0
krakatoaCommented:
Yes, it's always good to be faster, and two times faster is of course better. But in practical terms it is not quite so outstanding - Buffer and Builder share the same order of magnitude base, and although if you extrapolate my code's results you get nearer to a fourfold slowdown if you consider about a 1 second delay as being the first appreciable deficit amount, then you would notice only about a one-and-a-half second lag between the two methods over a distance of 3 million append()(s) -  enough to process each word in "War and Peace" 6 times over.

One would only want to use a synched approach if you needed that as such of course, but in sheer linear processing there's not much loose change.
0
gudii9Author Commented:
I ran the program got output

Buffer ops took 268234080(---->9 digit huge number)
Builder ops took 23028845(---->8 digit number way smaller than buffer)
Char array ops took 10564509(---->8 digit number almost half of above builder number)

String concat took 4593848 nanosecs to produce a string of length 10000000



      
sm.sb = new StringBuffer(loops);
      sm.sbldr = new StringBuilder(loops);
      sm.chA = new char[loops];

In above lines, I wonder  how are we are we able to call sm.sb, sm.sbldr since sb, sbldr etc are neither method names nor static variables.

     halfString = sm.sb.substring(0,sm.sb.length()/2).toString();
      otherHalfString = sm.sb.substring((sm.sb.length()/2)).toString();

I also wonder what we are trying to do in above two lines and as a whole what we are trying to prove in this program, Please advise
0
krakatoaCommented:
gudii9 -

sm is an instance of the StringMeter class, so it has the member vars of its class - the StringBuffer and StringBuilder. These are simply being accessed via the "." notation.

As for the concat(), this is just using the two halves of a large 1MB string which has already been created, and putting them back together again. It's only a loose use case which says that if you can achieve the concatenation of two such large chunks in that space of time, then use the result to estimate how that stacks up against other ways of doing the same thing. You could experiment with your own strings of different lengths to see what timings they give you for example.

The main focus of my comment and code was to obtain some ball-park comparisons between Buffer and Builder performance to help you in your question. But as Doug has said, there may be other considerations you need to take into account as well, and not just these crude timings.
0
Tamil ArasiAndroid DeveloperCommented:
Hi,
I hope this will be help to you,

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

Refer this links:
http://www.techtamasha.com/difference-between-string-and-stringbufferstringbuilder-in-java/28

http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java
0
krakatoaCommented:
@ by: TamilarasiSivarajPosted on 2013-10-24 at 08:56:14ID: 39596494

girionis already made this point.
0
dpearsonCommented:
BTW I just thought of perhaps a clearer way to explain the potential impact of using StringBuffer in a multithreaded application.

It's like if you were running a team race around a track and you need all members of your team to get to the end in order to finish - last one over the line is your time (this is how bike races work!).

If you use StringBuilder then all members of the team put their heads down and go as fast as they can (no "synchronize").

If you use StringBuffer then after each step or turn of the wheel everyone looks up and has to look to see where each of their teammates is now and then continues on (we're using "synchronize").

As you can imagine, the team with all that checking will be slower to get to the end of the race.  The more folks on your team, the worse it gets (everyone has more foks to check on).  They don't have to necessarily wait for each other at each step, but all of that checking and verifying slows the team as a whole down (Java memory model and synchronize behavior).

OK - maybe that's no clearer :)

But I think it is the practical key difference here.

Doug
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.