Java string concatenation '+' behavior: compiler-dependent optimization limits
0 reputation · 25 Apr 2021, 04:28 UTC
Goal
The objective is to determine the specific conditions under which different Java compilers translate the string concatenation operator (+) into StringBuilder append calls versus other strategies like String.concat.
Constraints & Uncertainty
According to the Java Language Specification (§15.18.1.2), implementations are permitted to use any strategy to evaluate string concatenation, meaning the exact behavior is not mandated. While Oracle's javac typically translates non-constant concatenation to StringBuilder, other compilers such as Eclipse ECJ may apply different heuristics or thresholds. This variance creates uncertainty when writing performance-critical code, as the generated bytecode may differ across environments, potentially impacting memory allocation and execution speed.
Unresolved Questions
- What are the specific thresholds or rules used by
javacto decide betweenStringBuilderandString.concatfor non-constant expressions? - How do the optimization strategies of Eclipse ECJ differ from OpenJDK regarding the translation of the
+operator? - Which bytecode patterns should be verified via
javap -cto confirm the compiler's chosen concatenation strategy?