The big advantage of option A, return x + creditCard.substring(15, 19); is that it is simple and clean and works in all versions of Java from 1 to 8 . If StringBuffer used in its compiled form, a simple recompilation for Java 5 or later will use StringBuilder instead. This flexibility is lost when working with a StringBuffer or StringBuilder manually.
The exact compiled form is not fixed. Since the semantics of the String.substring method String.substring not defined by the Java Language Specification, compilers usually do not touch this and compile it as a regular method call. The specification recommends that compiler providers use StringBuilder to concatenate strings (the + operator) whenever there is an advantage, and most compilers will do this, even if there is no benefit. Here both parameters x and the result of substring are String , so a simple String.concat will be simpler, but most compilers always use StringBuilder , compiling option A into the equivalent
return new StringBuilder().append(x).append(creditCard.substring(15, 19)).toString(); .
Comparing this typical form with your option B, we can conclude that option B has two performance advantages:
new StringBuilder(x) initializes a StringBuilder with a capacity of x.length()+16 , which is sufficient for the whole operation, while the default capacity new StringBuilder() , usually used for option A, is fixed at 16 characters, which skips the mark here, since we have the result of characters 19 , so the base array of characters will be redistributed and copied
sb.append(creditCard, 15, 19); copies four characters without having to create an intermediate String representation of these characters. The costs of a substring operation vary by implementation, for example. The Oracle implementation has undergone significant changes with version 1.7.0_06 ; starting with this version, the substring requires a new char[] array containing a copy of the damaged character data, since it does not support a separate offset and length field
But note that all these differences in options A and B only affect the formal description of the operation. What actually happens depends on the JVM / JRE, and as a rule, the Hotspot optimizer knows a lot of operations related to a string, and can smooth out operations or produce intermediate representations of strings. Thus, the result regarding performance is rather unpredictable and may be affected by minor changes in implementation .
That's why developers can stick with option A, which, as they say, is simpler and more readable, and only cares about performance, as soon as the profiler tells them that there is a performance problem that can be solved using StringBuilder manually.
source share