jump to navigation

String Buffer is Thread Safe August 20, 2006

Posted by Allu in JAVA.
trackback

java.lang.StringBuffer

  If you are using StringBuffer in a non-multithreaded environment (or you at least know that nobody will be modifying the StringBuffer at the same time you are, which is essentially a single-threaded environment) you will want to write your own StringBuffer (I use one called SuperStringBuffer) that does not synchronize it’s methods. Calling a synchronized method is about 4x slower than calling one that’s not synchronized).

  If you’re doing something like this:

StringBuffer b = new StringBuffer();
b.append(foo);
b.append(bar);
b.append(baz);

it’s considerably faster to do it like this:

StringBuffer b = new StringBuffer();
synchronized (b)
{
  b.append(foo);
  b.append(bar);
  b.append(baz);
}

because the former has to obtain three object locks, where as the latter only has to obtain one.

Advertisements

Comments»

No comments yet — be the first.

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

%d bloggers like this: