Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #4
See Also: JBuilder Papers

Manipulating strings
The topic of today is concatenating Strings and performance. String manipulation is something we do quite often in our applications (at least I do). One of the simplest methods to concatenate two Strings is by using the '+' operator. To append String s2 to s1 we simply use:

  s1 += s2
But Java provides more ways for concatenating Strings. The String class contains a instance method named concat(String s). To add a new String to a existing String we would code something like this:
  s1.concat(s2);
The java.lang.StringBuffer package is perfect for String manipulation. To use the StringBuffer for adding strings, we must first create the StringBuffer and after appending the new string, convert the StringBuffer to a String object.
  StringBuffer buf = new StringBuffer(s1);
  buf.append(s2);
  s1 = buf.toString();
Because we use JBuilder for our programming we have access to the borland.jbcl.util packages. This package contains a lot usefull utility classes. One of the classes is the FastStringBuffer. The name suggest it is a fast class. Well, we will see at our performance test.
  FastStringBuffer buf = new FastStringBuffer(s1);
  buf.append(s2);
  s1 = buf.toString();
Performance
When doing some tests, and a lot of repetitive String concatenation, we discover a big difference in performance. The fastest way to do String concatenation is using StringBuffers. The next best thing will be the FastStringBuffer, but it is slower than the normal StringBuffer, and isn't thread safe. And closing the line with a considerable slower performance, are the String.concat method and the + operator.

You can use the follwing applet to see for yourself how the different methods perform. The applet will append the given String a specified number of times (denoted by the user). This process will be repeated 100 times, and the total time is divided by 100 to get the average time.

Note: this applet will only work in JDK 1.1 compliant browsers, such as Netscape Navigator 4.05 (or higher) with JDK 1.1


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.