Name: skT88420 Date: 05/28/99
I am writing a parser in Java, trying to make it as fast as
possible. In order to do this I build tokens in a StringBuffer,
since it can be reused, and text is appended quickly. When it
comes time to see what is in that StringBuffer it has to be
converted to a String (for comparison with String.equals).
Although String(StringBuffer) saves some time by sharing the
character array with the new String, it still has to make
a new String object. Moreover, if the StringBuffer changes later,
it does copy the array of characters (even if the String has
been garbage collected). so in fact no time is really saved.
This could all be avoided by adding a method to String:
String.equals(StringBuffer)
This new method would compare the character arrays directly.
Although it might be argued that this violates good OO design,
the String class already has access to StringBuffer's character
array. (In String(StringBuffer))
I experimented with a new class java.lang.StringBufferComparer
which does just that, and found a nearly 20-fold speed
improvement over String.equals(StringBuffer.toString()).
(Review ID: 83634)
======================================================================