[Divunal-devel] StringBuffers/string manipulation optimization

James Knight jknight@MIT.EDU
Thu, 24 Jun 1999 18:32:22 -0400


If you have been writing verbs that do lots of String manipulation (okay,
this applies to almost all verbs. :P), this is for you...
In java,
String buffers are used by the compiler to implement the binary string
concatenation operator +. For example, the code:
  String x = "a" + 4 + "c";
is compiled to the equivalent of:
  String x = new StringBuffer().append("a").append(4).append("c").toString();
...
so what does this mean to you...
Basically, this is all fine, and you don't have to worry about it if you
just have one long line of +s. However, if you have a for loop, like this
(a shortened version of Inventory.java):
	String s = "You are ";
	Enumeration e = d.subject().things();
	if((e != null) && e.hasMoreElements())
	{
		Thing t = (Thing)e.nextElement()
		s +=t.the() + t.name()
	}
	player.hears(s);
You will get some pretty inefficient code.
The code above compiles to the equivilent of:
	String s = "You are ";
	Enumeration e = d.subject().things();
	if((e != null) && e.hasMoreElements())
	{
		Thing t = (Thing)e.nextElement()
		s = new
StringBuffer(s).append(t.the()).append(t.name()).toString();
	}
	player.hears(s);
This is very inefficient since it makes a new StringBuffer every time
through the loop.

If you instead change your code to explicitly use a StringBuffer, like so:
	StringBuffer s = new StringBuffer("You are ");
	Enumeration e = d.subject().things();
	if((e != null) && e.hasMoreElements())
	{
		Thing t = (Thing)e.nextElement()
		s.append(s).append(t.the()).append(t.name()).toString();
	}
	player.hears(s.toString());
the code will only make ONE StringBuffer the entire time, saving the
garbage collecter from much unnecessary work, and making your code faster.

So in summary, if you use keep appending stuff to a string on seperate
lines (or in a loop), you should be explicit and use a StringBuffer. If you
just have one line that does a+b+c+d+e, the compiler generates nice code
for you, so you don't have to worry about it.

(I've fixed all the bad places in the pump (including many in the
map-saving code), pending a checkin...)
-James

--
You are in a maze of testy little Java VMs, all subtly different.