I'm using StringBuilder, instead of String, in my code in effort
to make the code time-efficient during all that parsing & concatenation.
But when i look into its source, the substring() method of
AbstractStringBuilder and thus StringBuilder is returning a String and not a StringBuilder.
What would be the idea behind this ?
Thanks.
The reason the substring method returns an immutable String is that once you get a part of the string inside your StringBuilder, it must make a copy. It cannot give you a mutable "live view" into the middle of StringBuilder's content, because otherwise you would run into conflicts of which changes to apply to what string.
Since a copy is to be made anyway, it might as well be immutable: you can easily make it mutable if you wish by constructing a StringBuilder around it, with full understanding that it is detached from the mutable original.
To go from one StringBuilder to another containing a segment of the original, you could use:
StringBuilder original = ...;
StringBuilder sub = new StringBuilder().append(original, offset, length);
This could have been provided as a method of original, but as things stand it isn't.
This aside, you should profile your code before engaging in micro-optimisations of this sort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With