Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
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 += s2But 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
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