Even faster StringBuffer.append()

09 Jan 2006

Allan Caplan writes another fine PMD rule; this one, ConsecutiveLiteralAppends, catches code like this:

StringBuffer sb = new StringBuffer();

Those two StringBuffer.append invocations can be combined into one statement. Doing so knocks 17 bytes off the classfile size and eliminates a few instructions, including an invokevirtual. And of course it's a bit faster, too!

There's a threshold at which combining append calls makes the code less readable, so, as always, use your own judgement when applying this rule. But maybe this will turn up a few places where you can consolidate things - especially inside loops.

Thanks again to Allan for the nice rule! And props to him for writing a slew of unit tests for it; that should really help to reduce false positives.

Support PMD, get the book!