Java compiler doesn't optimize String concatenation automatically?
java, jsoup, optimization, performance, stringbuilder
Solution
This slow performance kind of surprises me because I was under the impression that Java compilers substitute expressions like A + B + C with new StringBuilder(A).append(B).append(C).toString().
And so the compiler creates the code:
for (Element el : els)
entireText = new StringBuilder(entireText).append(el.text()).toString();
You will need to create the StringBuilder outside the loop and append to it manually.
Problem
The following Jsoup code concatenates the text of all elements in container `els`: ``` for (Element el : els) entireText += el.text(); ``` On a container with ~64 elements, each containing ~1KB (totaling in entireText being ~64KB), this simple loop takes about 8 seconds on a typical low-end Android phone. This slow performance kind of surprises me because I was under the impression that Java compilers substitute expressions like `A + B + C` with `new StringBuilder(A).append(B).append(C).toString()`. Is that not the case? What am I missing?