Steve,

Maybe this is common knowledge, but you know never to do this right?

String x = "a" + "b";

You have to do something like this:

StringBuffer b = new StringBuffer();
b.append("a");
b.append("b");

Using StringBuffer vastly improves performance.

Ugh! This is like saying "never use goto". In this example, you are completely wrong:


String x = "a" + "b";

compiles to:

load x, "ab"

which is a lot better than:

getclass StringBuffer
dup
dup
new
load "a"
invoke "append"
load "b"
invoke "append"
store x

The Java compiler will take constant string expressions that are concatenated and perform the concatenation for you. The code is smaller.

However, if you are doing a lot of string (dynamic) processing, than using StringBuffer is to your advantage, because lots of string operations are converted (again, by the compiler) into uses of the StringBuffer class.

There's also nothing wrong with doing this:

String path = SOME_STOCK_PATH + argv[0];

Because if you want a String object that looks like "some/stock/path/mypath", and not a StringBuffer containing those characters, then why would you write this:

StringBuffer sb = new StringBuffer();
sb.append(SOME_STOCK_PATH);
sb.append(argv[0]);
String whatIreallyWanted = sb.toString();

This is exactly what the compiler will do with the code. You can't improve the speed, because you are just doing compiler work. What have you gained? Loss of readability, which I think is a poor tradeoff for no benefit.

There is one was to make it "better". Do this:

StringBuffer sb = new StringBuffer(SOME_STOCK_PATH).append(argv[0]);

or even

StringBuffer sb = new StringBuffer(SOME_STOCK_PATH.length() + argv[0].length()).append(SOME_STOCK_PATH).append(argv[0]);

At least then you'll have a somewhat appropriately sized array, and you'll avoid the re-allocation of arrays required to handle the string sizes.

Over the versions of the JVM, StringBuffer and String performance have been improved; the implementors know that String objects get created all the time and are used heavily in the standard library and pretty much everywhere else.

Bottom line: don't resort to "performance" "improvements" at the expense of readability of your code. I consider this to be a classic case of premature optimization.

-chris


--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to