You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[java] [doc] ConsecutiveAppendsShouldReuse is it really an optimization? #202
Description:
This is presented as a performance optimization. This is wrong, it doesn't really optimize anything and it's a waste of time to "fix". And if someone's code is more readable without it, they should avoid the "fix".
The description is misleading.
Code Sample demonstrating the issue:
Not relevant.
As seen, the appendPerLine variant produces a much larger bytecode, by producing several extra aload_1 and pop instructions. In turn, this means the JRE will produce a larger callsite and has a greater overhead. Smaller bytecode means not only less instructions to execute, but also higher chances of inlining by the JIT, which will further improve performance.
This alone improves the performance for a cold start. One could argue that the JRE should be able to optimize these instructions away once the VM has warmed up. However, this claim needs support, and would still only apply to long-running processes.
So, let's check this claim, and validate the performance even after warmup. Let's use JMH:
@jsotuyod Thank you very much for this analysis. My claims are based on the fact that the only reference I found to ConsecutiveAppendsShouldReuse is a StackOverflow post, with the consensus that this is a micro-optimizations that will be done by the runtime anyway.
I therefore suggest that you add reference in the docs, either to that link you provided or to a generalized version of your response.
None the less, this is something that the JVM is not currently optimizing, and for some programs may be of interest. This is certainly not the case for all programs (maybe not even most), but then it's up to the development team to choose which rules to enforce appropriately.
I agree on the need for better documentation, I'll take your advice and improve that rule's doc ASAP. We have plans on our roadmap to provide better default rulesets for new users.
It's true 'though that maybe that rule would fit better the optimization ruleset than the string ruleset.
Note that the best practice for using StringBuffer/Builder is still chaining the append() method calls. This is its design. So other than the micro-optimization, it's also a matter of style.
changed the title [-][Java] ConsecutiveAppendsShouldReuse is not really an optimization[/-][+][java] [doc] ConsecutiveAppendsShouldReuse is not really an optimization[/+]on Jan 27, 2017
changed the title [-][java] [doc] ConsecutiveAppendsShouldReuse is not really an optimization[/-][+][java] [doc] ConsecutiveAppendsShouldReuse is it really an optimization?[/+]on Jan 27, 2017
I'm not convinced. I haven't seen the sources of Benchmark, but I suspect it doesn't do anything with the strings, which makes the test artificial. Here is my benchmark that uses the strings (adds up their length), and I don't get significant differences, at least not anything like 4x. (In fact, sometimes it's even faster without chaining):
`
public class StringBuilderChainingMicrobenchmark {
private static final int LOOP_LENGTH = 50_000_000;
private static final int STRING_LENGTH = 1377777780;
private String d = "d....";
private String e = "e...";
public static void main(String[] args) {
new StringBuilderChainingMicrobenchmark().benchmark();
}
private void benchmark() {
Microbenchmarker.benchmark("chained", () -> chained());
Microbenchmarker.benchmark("unchained", () -> unchained());
}
private static void assertLength(int sum) {
if (sum != STRING_LENGTH) {
throw new IllegalStateException("Incorrect string length: " + sum);
}
}
private void chained() {
int sum = 0;
for (int i = 0; i < LOOP_LENGTH; i++) {
sum += stringBuiltWithChaining(i).length();
}
assertLength(sum);
}
private void unchained() {
int sum = 0;
for (int i = 0; i < LOOP_LENGTH; i++) {
sum += stringBuiltWithoutChaining(i).length();
}
assertLength(sum);
}
private String stringBuiltWithChaining(int i) {
StringBuilder b = new StringBuilder();
b.append("a").append(i).append("b").append(i).append("c").append(d)
.append(e);
return b.toString();
}
private String stringBuiltWithoutChaining(int i) {
StringBuilder b = new StringBuilder();
b.append("a");
b.append(i);
b.append("b");
b.append(i);
b.append("c");
b.append(d);
b.append(e);
return b.toString();
}
}
`
And this is my Microbenchmark.java:
`
public class Microbenchmarker {
public static void benchmark(String name, Runnable task) {
for (int i = 0; i < 3; i++) {
System.out.println("Calling gc");
System.gc();
System.out.println("Warming up " + name);
task.run();
}
System.out.println("Calling gc");
System.gc();
System.out.println("Running " + name);
long t1 = System.nanoTime();
task.run();
long t2 = System.nanoTime();
double secondsTaken = (t2 - t1) / 1000D / 1000D;
System.out.println("Task " + name + " took " + secondsTaken + "ms");
}
}
`
An example output:
Calling gc
Warming up chained
Calling gc
Warming up chained
Calling gc
Warming up chained
Calling gc
Running chained
Task chained took 6799.459034ms
Calling gc
Warming up unchained
Calling gc
Warming up unchained
Calling gc
Warming up unchained
Calling gc
Running unchained
Task unchained took 6620.444455ms
I'll add my comment since this is now the #1 search result for "ConsecutiveAppendsShoudlReuse" which I came across in my PMD report. This rule is a total waste of time and will be disabled in my project immediately. Donald Knuth said, "Premature optimization is the root of all evil." And this exemplifies premature optimization. Of all the top performance bottlenecks in your software, I can guarantee that you won't find the difference between an inline append or per-line append to be one of them.
There's also longstanding guidance to the Java community in Effective Java chapter 67 about knowing when to optimize. It would be wise to pay attention
@scottashipp Indeed. It's extremely difficult to see any performance differences in real life, and my test code above shows that even isolated microbenchmarking shows very little difference, and possibly even supports inverting this rule. Anyway, as you said, rules like this are a complete waste of time and only encourage a wrong mindset. The burden of proof is always on the side that demands new optimizations. I think the PMD project and its users would only benefit if this rule was simply deleted.
So I would say that this ticket about a rule of premature optimization was prematurely closed. Not a biggie, since this can be disabled by configuration, but still. Projects like PMD are in a good position to not only give tools but also document wise usage of them.
Activity
jsotuyod commentedon Jan 22, 2017
@noamtamim thanks for your comments. I'd like to know however what you base them on to support your claims.
In the meantime, I'd gladly show you what evidence supports this rule:
Let's start by analyzing javac output. Given the code:
We compile with javac, and check the output with
javap -c -sAs seen, the
appendPerLinevariant produces a much larger bytecode, by producing several extraaload_1andpopinstructions. In turn, this means the JRE will produce a larger callsite and has a greater overhead. Smaller bytecode means not only less instructions to execute, but also higher chances of inlining by the JIT, which will further improve performance.This alone improves the performance for a cold start. One could argue that the JRE should be able to optimize these instructions away once the VM has warmed up. However, this claim needs support, and would still only apply to long-running processes.
So, let's check this claim, and validate the performance even after warmup. Let's use JMH:
We compile and run it and we obtain:
So, even after warming up, following the rule produces a ~4X improvement in throughput.
Of course, you don't have to believe me, others have done similar analysis and you can even try it yourself.
noamtamim commentedon Jan 22, 2017
@jsotuyod Thank you very much for this analysis. My claims are based on the fact that the only reference I found to
ConsecutiveAppendsShouldReuseis a StackOverflow post, with the consensus that this is a micro-optimizations that will be done by the runtime anyway.I therefore suggest that you add reference in the docs, either to that link you provided or to a generalized version of your response.
Thanks again!
jsotuyod commentedon Jan 23, 2017
@noamtamim glad I could help.
Well, this certainly is a micro optimization. Most programs should first focus on sorting out big algorithmic issues reducing complexity, but once that is done, even small changes in critical paths can have a big effect. For instance, we recently obtained a 15% performance boost (~3.4 secs) on PMD execution by simply changing a
.substring(xxx).endsWith(".")with.charAt(xxx) == '.'.None the less, this is something that the JVM is not currently optimizing, and for some programs may be of interest. This is certainly not the case for all programs (maybe not even most), but then it's up to the development team to choose which rules to enforce appropriately.
I agree on the need for better documentation, I'll take your advice and improve that rule's doc ASAP. We have plans on our roadmap to provide better default rulesets for new users.
It's true 'though that maybe that rule would fit better the
optimizationruleset than thestringruleset.noamtamim commentedon Jan 23, 2017
Note that the best practice for using StringBuffer/Builder is still chaining the append() method calls. This is its design. So other than the micro-optimization, it's also a matter of style.
Thanks again for your time.
Improve docs on ConsecutiveAppendsShouldReuse
[-][Java] ConsecutiveAppendsShouldReuse is not really an optimization[/-][+][java] [doc] ConsecutiveAppendsShouldReuse is not really an optimization[/+]Improve docs on ConsecutiveAppendsShouldReuse
[-][java] [doc] ConsecutiveAppendsShouldReuse is not really an optimization[/-][+][java] [doc] ConsecutiveAppendsShouldReuse is it really an optimization?[/+]wipu commentedon Jan 17, 2020
I'm not convinced. I haven't seen the sources of Benchmark, but I suspect it doesn't do anything with the strings, which makes the test artificial. Here is my benchmark that uses the strings (adds up their length), and I don't get significant differences, at least not anything like 4x. (In fact, sometimes it's even faster without chaining):
`
public class StringBuilderChainingMicrobenchmark {
}
`
And this is my Microbenchmark.java:
`
public class Microbenchmarker {
}
`
An example output:
Calling gc
Warming up chained
Calling gc
Warming up chained
Calling gc
Warming up chained
Calling gc
Running chained
Task chained took 6799.459034ms
Calling gc
Warming up unchained
Calling gc
Warming up unchained
Calling gc
Warming up unchained
Calling gc
Running unchained
Task unchained took 6620.444455ms
scottashipp commentedon Aug 8, 2025
I'll add my comment since this is now the #1 search result for "ConsecutiveAppendsShoudlReuse" which I came across in my PMD report. This rule is a total waste of time and will be disabled in my project immediately. Donald Knuth said, "Premature optimization is the root of all evil." And this exemplifies premature optimization. Of all the top performance bottlenecks in your software, I can guarantee that you won't find the difference between an inline append or per-line append to be one of them.
There's also longstanding guidance to the Java community in Effective Java chapter 67 about knowing when to optimize. It would be wise to pay attention
wipu commentedon Aug 13, 2025
@scottashipp Indeed. It's extremely difficult to see any performance differences in real life, and my test code above shows that even isolated microbenchmarking shows very little difference, and possibly even supports inverting this rule. Anyway, as you said, rules like this are a complete waste of time and only encourage a wrong mindset. The burden of proof is always on the side that demands new optimizations. I think the PMD project and its users would only benefit if this rule was simply deleted.
So I would say that this ticket about a rule of premature optimization was prematurely closed. Not a biggie, since this can be disabled by configuration, but still. Projects like PMD are in a good position to not only give tools but also document wise usage of them.